如何以不同的用户身份继续执行python脚本
我想执行一个python脚本,该脚本按顺序执行以下命令:如何以不同的用户身份继续执行python脚本,python,Python,我想执行一个python脚本,该脚本按顺序执行以下命令: sudo su - postgres #change user to postgres psql #enter the psql command promt from create user user_name with password 'mypassword'; # create database voylla_development with en
sudo su - postgres #change user to postgres
psql #enter the psql command promt from
create user user_name with password 'mypassword'; #
create database voylla_development with encoding = 'utf8'; #all the 3 commands are to be executed in psql command prompt
grant all on database voylla_development to user_name; #
exit #psql prompt
exit #postgres user
cat <backup_file_name> | zcat - | PGPASSWORD=mypassword psql -d voylla_development -h localhost -p 5432 -U user_name
但在我以postgres用户身份登录后,脚本停止。用户更改后如何继续脚本?
谢谢
编辑:使用psycopg2帮助解决问题创建新的
Popen()
对象时,启动一个新程序。您没有与打开的psql
shell通信
您可以通过将stdin
设置为subprocess.PIPE
直接驱动psql
,或者更简单地使用来驱动psql
shell:
import pexpect
psql = pexpect.spawn('psql')
psql.expect('=>') # wait for the prompt
psql.send('create user user_name with password 'mypassword';')
# etc.
Popen()
实例是独立的进程;你没有保留外壳。@MartijnPieters:我怎么做(保留外壳)?是否可以使用subprocess,或者我应该寻找其他东西?为什么不以root用户身份运行Python脚本呢sudoyourscript.py
。没有帮助…同样的事情再次发生,这是一个单独的问题;同样的话,使用psql
的会话不会转到新命令。第二个Popen()
实例运行一个新程序,它不会向旧程序发送命令。使用pexpect
或直接写入第一个Popen()进程的stdin
。
import pexpect
psql = pexpect.spawn('psql')
psql.expect('=>') # wait for the prompt
psql.send('create user user_name with password 'mypassword';')
# etc.