简体   繁体   English

从主脚本并行运行多个 python 脚本

[英]Run multiple python scripts in parallel from master script

I'd like to run multiple python scripts in parallel and start them from a master script.我想并行运行多个 python 脚本并从主脚本启动它们。 I did find solutions for this in previously asked questions, however, none of these worked if the scripts running in parallel contained loops.我确实在之前提出的问题中找到了解决方案,但是,如果并行运行的脚本包含循环,这些都不起作用。 Let's for example define two scripts.例如,让我们定义两个脚本。

Script 1:脚本 1:

array_1 = []

x = 0
while True:
    array_1.append(x)
    x = x + 1

Script 2:脚本2:

array_2 = []

x = 0
while True:
    array_2.append(x)
    x = x + 1

Now I want to run both processes simultaneously.现在我想同时运行两个进程。 Previous solutions suggested the following code for a master script:以前的解决方案为主脚本建议了以下代码:

import script_1, script_2

exec(open(script_1))
exec(open(script_2))

While this is a solution for starting scripts from within another script, however, this will not run the two scripts in parallel.虽然这是从另一个脚本中启动脚本的解决方案,但是,这不会并行运行两个脚本。 What should such a master script actually look like ?这样的主脚本实际上应该是什么样的?

Thanks for your suggestions!感谢您的建议!

Edit编辑

I tried the following threading approach:我尝试了以下线程方法:

def function_1():
print('function 1 started...')
    while True:
        print('1')
        sleep(1)

def function_2():
print('function 2 started...')
    while True:
        print('2')
        sleep(1)

thread_1 = Thread(target=function_1())
thread_2 = Thread(target=function_2())
thread_1.start()
thread_2.start()


thread_1.join()
thread_2.join()
print("thread finished")

It doesn't work, only the first function gets started so I get the following output:它不起作用,只有第一个函数启动,所以我得到以下输出:

function 1 started...
1
1
1
1
1
1

When you want to spawn a new thread, you need to pass the address of the function you want the thread to execute, and not to call it.当你想产生一个新线程时,你需要传递你想让线程执行的函数的地址,而不是调用它。 What you are doing here is essentially spawning a new thread that immediately calls function_1() which of course runs forever.您在这里所做的基本上是产生一个新线程,该线程立即调用function_1() ,该线程当然会永远运行。

Also, you won't be able to reach this line of code:此外,您将无法访问这行代码:

print("thread finished")

As the threads are executing a while loop - forever, so it is redundent..由于线程正在执行 while 循环 - 永远,所以它是冗余的..

from time import sleep
from threading import Thread


def function_1():
    print('function 1 started...')
    while True:
        print('1')
        sleep(1)


def function_2():
    print('function 2 started...')
    while True:
        print('2')
        sleep(1)


thread_1 = Thread(target=function_1)
thread_2 = Thread(target=function_2)
thread_1.start()
thread_2.start()

thread_1.join()
thread_2.join()
# print("thread finished") - redundant

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

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