[英]Run multiple bash commands simultaneously in Python
I want to create a python script that can start multiple instances of a bash script. 我想创建一个可以启动bash脚本的多个实例的python脚本。
I have tried 我努力了
import subprocess
commands = '''
bashcmd1
bashcmd2
bashcmd3
'''
process = subprocess.Popen('/bin/bash', stdin=subprocess.PIPE, stdout=subprocess.PIPE)
out, err = process.communicate(commands)
print out
But it stops at bashcmd2 and continues only if i hit CTRL+C . 但是它在bashcmd2处停止,并且仅在我按CTRL + C时才继续。
you're just running one bash with 3 commands in it. 您只运行了一个带有3个命令的bash。
If the commands aren't setting variables or depending from each other (else you would not be able to parallelize them), maybe you could create 3 subprocess.Popen
instances instead: 如果这些命令不是设置变量或彼此依赖(否则您将无法并行化它们),则可以创建3
subprocess.Popen
实例代替:
commands = '''
bashcmd1
bashcmd2
bashcmd3
'''
for process in [subprocess.Popen(['/bin/bash', '-c', line], stdout=subprocess.PIPE)
for line in commands.split("\n") if line]: # filter out blank lines
out, err = process.communicate() # or just rc = process.wait()
# print out & err
that command first create a list comprehension of Popen
objects (list not generator so the processes start immediately), then perform a communicate
to wait for completion (but other processes are running in the meanwhile) 该命令首先创建
Popen
对象的列表理解(列表不是生成器,所以进程立即启动),然后执行communicate
以等待完成(但其他进程正在运行)
The upside is that you can apply this technique to any script containing commands, and you don't need to use the shell &
capability (more portable, including Windows provided you're using ["cmd","/c"
prefix instead of bash
) 好处是,您可以将此技术应用于包含命令的任何脚本,并且不需要使用shell
&
功能(更具移植性,包括Windows,前提是您使用的是["cmd","/c"
前缀而不是bash
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.