2012-03-10 377 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 
相關問題