我希望並行運行兩個可執行文件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