如何以不同的用户继续执行python脚本

时间:2013-09-20 17:14:39

标签: 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 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

我尝试使用subprocess和os.system():

cmd='sudo -u postgres psql'
args = shlex.split(cmd)
p=subprocess.Popen(args)
p.wait()

cmd1='psql'
args1 = shlex.split(cmd1)
p=subprocess.Popen(args1)
p.wait()

##and so on for each command

但是我以postgres用户身份登录后脚本停止了。用户更改后如何继续脚本? 感谢

编辑:使用psycopg2帮助了原因

1 个答案:

答案 0 :(得分:1)

创建新的Popen()对象时,启动 new 程序。您没有与开放的psql shell进行通信。

您必须通过将psql设置为stdin来直接驾驶subprocess.PIPE,或者更轻松地使用pexpect来驾驶psql shell:< / p>

import pexpect

psql = pexpect.spawn('psql')
psql.expect('=>')  # wait for the prompt
psql.send('create user user_name with password 'mypassword';')
# etc.