2012-03-10 9 views
3

同じプロセスでプロセスを開き、2つのコマンドを実行したいとします。私は:Python:popenを使用して1つのプロセスで複数のコマンドを実行する方法

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() 

私は2回popenを使用する場合、これらの2つのコマンドは異なるプロセスで実行されます。しかし、私はそれらを同じシェルで走らせたい。

答えて

5

コマンドは、常に2つ(UNIX)のプロセスになりますが、あなたは使用して1つの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 
関連する問題