How do I execute multiple shell commands with a single python subprocess call?

余生长醉 提交于 2021-01-21 05:07:52

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/39725120/how-do-i-execute-multiple-shell-commands-with-a-single-python-subprocess-call

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