Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/297.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何以不同的用户身份继续执行python脚本_Python - Fatal编程技术网

如何以不同的用户身份继续执行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

我想执行一个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
但在我以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.