我想打开一个进程并在同一个进程中运行两个命令。我有 :
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 中运行。
最佳答案
这些命令将始终是两个(unix)进程,但您可以通过一次调用 Popen
来启动它们。和使用相同的 shell :
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
关于python-2.7 - python : How to run multiple commands in one process using popen,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9649355/