如何使用单个 python 子进程调用执行多个 shell 命令? [英] How do I execute multiple shell commands with a single python subprocess call?
问题描述
理想情况下,它应该像一个命令列表,我想使用单个子进程调用来执行和执行所有这些命令.我能够通过将所有命令存储为 shell 脚本并使用子进程调用该脚本来做类似的事情,但我想要一个纯 python 解决方案.我将使用 shell=True 执行命令,是的,我理解风险.
如果它们是独立的,请使用分号链接它们.
例如(Python 3)
<预><代码>>>>导入子流程>>>result = subprocess.run('echo Hello ; echo World', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)>>>结果CompletedProcess(args='echo Hello ; echo World', returncode=0, stdout=b'Hello\nWorld\n')但从技术上讲,这不是纯 Python 解决方案,因为 shell=True
.arg 处理实际上是由 shell 完成的.(您可以将其视为执行 /bin/sh -c "$your_arguments"
)
如果你想要一个更纯粹的解决方案,你必须使用 shell=False
并循环你的几个命令.据我所知,没有办法直接用子进程模块启动多个子进程.
Ideally it should be like a list of commands that I want to execute and execute all of them using a single subprocess call. I was able to do something similar by storing all the commands as a shell script and calling that script using subprocess, but I want a pure python solution.I will be executing the commands with shell=True and yes I understand the risks.
Use semicolon to chain them if they're independent.
For example, (Python 3)
>>> import subprocess
>>> result = subprocess.run('echo Hello ; echo World', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
>>> result
CompletedProcess(args='echo Hello ; echo World', returncode=0, stdout=b'Hello\nWorld\n')
But technically that's not a pure Python solution, because of shell=True
. The arg processing is actually done by shell. (You may think of it as of executing /bin/sh -c "$your_arguments"
)
If you want a somewhat more pure solution, you'll have to use shell=False
and loop over your several commands. As far as I know, there is no way to start multiple subprocesses directly with subprocess module.
这篇关于如何使用单个 python 子进程调用执行多个 shell 命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!