在python中开发并行运行同一文件的脚本

2024-10-03 09:17:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个python脚本,它调用另一个python文件并运行它。但是,我需要脚本并行运行同一个文件多次。我将在这里分享代码片段。这将运行python文件一次。你知道吗

output = os.popen('python py_generator_sm20.py' + options)
print output.read()

如何将其并行化以同时运行多次?你知道吗


Tags: 文件代码py脚本readoutputosgenerator
2条回答

我想你需要这个:

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)

这可能不是完整的答案,因为这是代码的一部分,但可能是一个起点。使用multiprocessing模块可以创建一个工作线程池,然后使用subprocess模块可以为每个工作线程和check the output调用脚本的一个实例:

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

正如你所看到的,它们同时运行。你知道吗

相关问题 更多 >