简体   繁体   English

并行运行多个python文件

[英]Running multiple python files in parallel

The following is my code. 以下是我的代码。 It's quite simple and straight forward, and the mission is to run three files at the same time. 它非常简单直接,任务是同时运行三个文件。

When I ran it, it only runs the last processes (each file should generate a csv file). 当我运行它时,它只运行最后的进程(每个文件应该生成一个csv文件)。

import multiprocessing
import subprocess

def worker(file):
    subprocess.call(["python", file])


if __name__ == '__main__':
    files = ["launch_day_t1.py","launch_day_t2.py","launch_day_t3.py"]
    for i in files:
        p = multiprocessing.Process(target=worker(i))
        p.start()

As you can see I have three files ("launch_day_t1.py","launch_day_t2.py" and "launch_day_t3.py") that I wish to run. 如您所见,我希望运行三个文件(“launch_day_t1.py”,“launch_day_t2.py”和“launch_day_t3.py”)。

My question is that whether is this the best way to run parallel scripts (if it is), or is there a better approach? 我的问题是,这是否是运行并行脚本的最佳方式(如果是),还是有更好的方法?

Thanks! 谢谢!

The best situation here would be to refactor the code in "launch_day_t1.py" so that the parts you need to call are wrapped into functions, and the cli code is if __name_=="__main__" 'd... something that looks like: 这里最好的情况是重构“launch_day_t1.py”中的代码,以便你需要调用的部分被包装到函数中,而cli代码是if __name_=="__main__" 'd ......看起来像:

#launch_day_t1.py
def do_stuff():
    pass
def do_more_stuff():
    pass
if __name__ == "__main__":
    do_stuff()
    do_more_stuff()

Then instead of calling the file from the command line, you can import the parts that you need, and call it from your existing python interpreter, and that will make things like gathering up the output and such much easier. 然后,您可以导入所需的部件,而不是从命令行调用该文件,并从现有的python解释器中调用它,这将使收集输出变得更容易。

import multiprocessing
import subprocess
import launch_day_t1
import launch_day_t2

def worker(namespace):
    namespace.do_stuff()
    return namespace.do_more_stuff()


if __name__ == '__main__':
    N_CORES = 8
    files = [launch_day_t1, launch_day_t2]
    p = multiprocessing.Pool(2*N_CORES)
    print(p.map(worker, files))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM