Python:如何使用 popen 在一个进程中运行多个命令 [英] Python: How to run multiple commands in one process using popen

查看:93
本文介绍了Python:如何使用 popen 在一个进程中运行多个命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

如果我两次使用popen,这两个命令会在不同的进程中执行.但我希望它们在同一个 shell 中运行.

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.

推荐答案

这些命令将始终是两个 (unix) 进程,但您可以通过对 Popen 和同一个 shell 的一次调用来启动它们使用:

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

这篇关于Python:如何使用 popen 在一个进程中运行多个命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆