我希望并行运行两个可执行文件a.exe和b.exe,一个接一个地调用。在Python中使用os.system()并行运行两个可执行文件?
当我想,
os.system('a.exe')
#some code
os.system('b.exe')
B.EXE是起步后,才杀了a.exe的? 为什么会发生? 我怎样才能同时运行两个? (我需要做的多线程?) 注:我在Windows平台
我希望并行运行两个可执行文件a.exe和b.exe,一个接一个地调用。在Python中使用os.system()并行运行两个可执行文件?
当我想,
os.system('a.exe')
#some code
os.system('b.exe')
B.EXE是起步后,才杀了a.exe的? 为什么会发生? 我怎样才能同时运行两个? (我需要做的多线程?) 注:我在Windows平台
尝试运行每一个作为一个单独的线程:
import thread
thread.start_new_thread(os.system, ('a.exe',))
thread.start_new_thread(os.system, ('b.exe',))
你可能想尝试subprocess.Popen
,这允许进程执行但不会阻止。但是在这个例子中你必须考虑僵尸进程。
您可以使用特定的方式来运行两个或多个命令或programms的,如线程库的Python。这里有一个关于它如何工作的广泛例子。
import threading
import time
exitFlag = 0
class myThread (threading.Thread):
def __init__(self, threadID, name, counter):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.counter = counter
def run(self):
print "Starting " + self.name
print_time(self.name, self.counter, 5)
print "Exiting " + self.name
def print_time(threadName, delay, counter):
while counter:
if exitFlag:
threadName.exit()
time.sleep(delay)
print "%s: %s" % (threadName, time.ctime(time.time()))
counter -= 1
# Create new threads
thread1 = myThread(1, "Thread-1", 1)
thread2 = myThread(2, "Thread-2", 2)
# Start new Threads
thread1.start()
thread2.start()
print "Exiting Main Thread"
然后,你的代码可能是这样的:
import threading
class myThread (threading.Thread):
def __init__(self, command):
threading.Thread.__init__(self)
self.cmd = command
def run(self):
print "Starting " + self.cmd
os.system(self.cmd)
print "Exiting " + self.cmd
lstCmd=["a.exe","b.exe","ping 192.168.0.10","some command"]
# Create new threads
thread1 = myThread(lstCmd[0])
thread2 = myThread(lstCmd[1])
thread3 = myThread(lstCmd[2])
thread4 = myThread(lstCmd[3])
# Start new Threads
thread1.start()
thread2.start()
thread3.start()
thread4.start()
如果我们忽略例外那么简单,同时运行几个程序:
#!/usr/bin/env python
import subprocess
# start all programs
processes = [subprocess.Popen(program) for program in ['a', 'b']]
# wait
for process in processes:
process.wait()
见Python threading multiple bash subprocesses?
如果你想停止以前启动的进程,如果任何程序失败ls开始:
#!/usr/bin/env python3
from contextlib import ExitStack
from subprocess import Popen
def kill(process):
if process.poll() is None: # still running
process.kill()
with ExitStack() as stack: # to clean up properly in case of exceptions
processes = []
for program in ['a', 'b']:
processes.append(stack.enter_context(Popen(program))) # start program
stack.callback(kill, processes[-1])
for process in processes:
process.wait()
这是我找到的最好的解决方案,因为它的简单性。其他解决方案显示产生n个进程的好方法,这对于产生一个异步进程而不会阻塞程序的其余部分是很好的。 – robm