0

我想执行一个 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

我尝试使用子进程和 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 帮助解决了这个问题

4

1 回答 1

1

当您创建一个新Popen()对象时,您将启动一个程序。您没有与打开的psql外壳通信。

您要么必须psql通过设置stdin来直接驱动subprocess.PIPE,要么更容易地使用pexpect来驱动psql外壳:

import pexpect

psql = pexpect.spawn('psql')
psql.expect('=>')  # wait for the prompt
psql.send('create user user_name with password 'mypassword';')
# etc.
于 2013-09-20T18:15:48.060 回答