我想打开一个进程并在同一进程中运行两个命令.我有 :
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()
Run Code Online (Sandbox Code Playgroud)
如果我使用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()
Run Code Online (Sandbox Code Playgroud)
运行程序后,文件'log'包含:
hello world
total 4
-rw-rw-r-- 1 anthon users 303 2012-05-15 09:44 test.py
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16645 次 |
| 最近记录: |