2012-03-10 38 views
3

我想打开一个进程并在同一进程中运行两个命令。我有:Python:如何在一个进程中使用popen运行多个命令

cmd1 = 'source /usr/local/../..' 
cmd2 = 'ls -l' 
final = Popen(cmd2, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True) 
stdout, nothing = final.communicate() 
log = open('log', 'w') 
log.write(stdout) 
log.close() 

如果我使用popen两次,这两个命令将在不同的进程中执行。但我希望它们在同一个shell中运行。

回答

5

的命令将始终是两个(UNIX)进程,但你可以从一个呼叫Popen和相同的外壳用其启动:

from subprocess import Popen, PIPE, STDOUT 

cmd1 = 'echo "hello world"' 
cmd2 = 'ls -l' 
final = Popen("{}; {}".format(cmd1, cmd2), shell=True, stdin=PIPE, 
      stdout=PIPE, stderr=STDOUT, close_fds=True) 
stdout, nothing = final.communicate() 
log = open('log', 'w') 
log.write(stdout) 
log.close() 

运行程序文件“登录”包含后:

hello world 
total 4 
-rw-rw-r-- 1 anthon users 303 2012-05-15 09:44 test.py 
相关问题