Python 使用子进程运行多个 bash 命令
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17742789/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
running multiple bash commands with subprocess
提问by Paul
If I run echo a; echo b
in bash the result will be that both commands are run. However if I use subprocess then the first command is run, printing out the whole of the rest of the line.
The code below echos a; echo b
instead of a b
, how do I get it to run both commands?
如果我echo a; echo b
在 bash 中运行,结果将是两个命令都运行。但是,如果我使用 subprocess 则运行第一个命令,打印出该行的其余部分。下面的代码回显a; echo b
而不是a b
,我如何让它运行这两个命令?
import subprocess, shlex
def subprocess_cmd(command):
process = subprocess.Popen(shlex.split(command), stdout=subprocess.PIPE)
proc_stdout = process.communicate()[0].strip()
print proc_stdout
subprocess_cmd("echo a; echo b")
采纳答案by bougui
You have to use shell=True in subprocess and no shlex.split:
你必须在子进程中使用 shell=True 而没有 shlex.split:
def subprocess_cmd(command):
process = subprocess.Popen(command,stdout=subprocess.PIPE, shell=True)
proc_stdout = process.communicate()[0].strip()
print proc_stdout
subprocess_cmd('echo a; echo b')
returns:
返回:
a
b
回答by David.Zheng
>>> command = "echo a; echo b"
>>> shlex.split(command);
['echo', 'a; echo', 'b']
so, the problem is shlex module do not handle ";"
所以,问题是 shlex 模块不处理“;”
回答by admenva
I just stumbled on a situation where I needed to run a bunch of lines of bash code (not separated with semicolons) from within python. In this scenario the proposed solutions do not help. One approach would be to save a file and then run it with Popen
, but it wasn't possible in my situation.
我只是偶然发现了一种情况,我需要在 python 中运行一堆 bash 代码(不以分号分隔)。在这种情况下,建议的解决方案无济于事。一种方法是保存文件然后使用 运行它Popen
,但在我的情况下这是不可能的。
What I ended up doing is something like:
我最终做的是这样的:
commands = '''
echo "a"
echo "b"
echo "c"
echo "d"
'''
process = subprocess.Popen('/bin/bash', stdin=subprocess.PIPE, stdout=subprocess.PIPE)
out, err = process.communicate(commands)
print out
So I first create the child bash process and after I tell it what to execute. This approach removes the limitations of passing the command directly to the Popen
constructor.
所以我首先创建子 bash 进程,然后告诉它要执行什么。这种方法消除了将命令直接传递给Popen
构造函数的限制。
回答by FrancisWolcott
Join commands with "&&".
用“&&”连接命令。
os.system('echo a > outputa.txt && echo b > outputb.txt')
回答by Pierz
If you're only running the commands in one shot then you can just use subprocess.check_output
convenience function:
如果您只是一次性运行命令,那么您可以使用subprocess.check_output
便利功能:
def subprocess_cmd(command):
output = subprocess.check_output(command, shell=True)
print output