Python: How to run multiple commands in one process using popen

孤者浪人 提交于 2021-02-19 01:20:29

问题


I want to open a process and run two commands in the same process. I have :

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

If I use popen two times, these two commands will be executed in different processes. But I want them to run in the same shell.


回答1:


The commands will always be two (unix) processes, but you can start them from one call to Popen and the same shell by using:

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

After running the program the file 'log' contains:

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


来源:https://stackoverflow.com/questions/9649355/python-how-to-run-multiple-commands-in-one-process-using-popen

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!