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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 09:03:33  来源:igfitidea点击:

running multiple bash commands with subprocess

pythonbashsubprocess

提问by Paul

If I run echo a; echo bin 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 binstead 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 Popenconstructor.

所以我首先创建子 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_outputconvenience function:

如果您只是一次性运行命令,那么您可以使用subprocess.check_output便利功能:

def subprocess_cmd(command):
    output = subprocess.check_output(command, shell=True)
    print output