且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用Popen在一个进程中运行多个命令?

更新时间:2022-06-22 04:23:34

命令始终是两个(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()

运行程序后,文件"log"包含:

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