python-2.7 - python : How to run multiple commands in one process using popen

标签 python-2.7

我想打开一个进程并在同一个进程中运行两个命令。我有 :

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/

相关文章:

python-2.7 - Hadoop Streaming 永无止境

Python 代码在某些版本中无法运行

python-2.7 - pymc3 多重高斯过程回归

python-2.7 - OpenCV 3.2 CUDA 支持 python

Python 打开和关闭文件 - 不直观

python - 我在哪里可以获得模糊的 DLL,以便 py2exe 编译?

python - 无法在谷歌应用引擎服务上设置手动缩放

python - 如何在centos中通过浏览器运行python脚本

python - some_string 中的 empty_string - 总是正确的?

python - 使用 PIL 将 RGB 图像变成纯黑白图像