[英]developing a script running the same file in parallel in python
我有一個python腳本,它調用另一個python文件並運行它。 但是,我需要該腳本多次並行運行同一文件。 我將在這里共享代碼片段。這將運行一次python文件。
output = os.popen('python py_generator_sm20.py' + options)
print output.read()
如何使其並行運行多次?
由於代碼的
使用output
部分,這可能無法完全回答您,但可能是一個起點。
multiprocessing
模塊,您可以創建一個工作池,然后使用subprocess
模塊,可以為每個工作器調用腳本的一個實例,並檢查輸出 :
import multiprocessing as mp
import subprocess as sp
# an example with two runs
commands = ['python test.py', 'python test.py']
# pass the number of threads that will be working
# if the number of threads < len(commands) the exceed
# will run in sequence when some process terminate
pool = mp.Pool(processes=2)
# execute the script calls
res = pool.map(sp.check_output, commands)
print(*[item.decode() for item in res])
pool.close()
注意: check_output
的返回是一個byte string
,因此您需要將其轉換回string
我使用以下簡單程序對其進行了測試:
import time
if __name__ == "__main__":
print("Running an instance at {}".format(time.ctime()))
time.sleep(2)
print("Finished at {}".format(time.ctime()))
這就是輸出:
Running an instance at Thu Oct 11 23:21:44 2018
Finished at Thu Oct 11 23:21:46 2018
Running an instance at Thu Oct 11 23:21:44 2018
Finished at Thu Oct 11 23:21:46 2018
如您所見,它們同時運行。
我認為您需要這樣做:
from multiprocessing.dummy import Pool as ThreadPool
pt = ThreadPool(4)
results = pt.map(pt_function, pt_array)
或者也許是這種方式(如果您有很多線程腳本):
from Threading_orders import Thread
class First_time(Thread):
"""
A threading example
"""
def __init__(self, a, b):
"""Инициализация потока"""
Thread.__init__(self)
self.a = a
self.b = b
def run(self):
MyThread_1(self.a, self.b)
MyThread_2(self.a, self.b)
MyThread_3(self.a, self.b)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.