我想并行運行多個 python 腳本并從主腳本啟動它們。我確實在之前提出的問題中找到了解決方案,但是,如果并行運行的腳本包含回圈,這些都不起作用。例如,讓我們定義兩個腳本。
腳本 1:
array_1 = []
x = 0
while True:
array_1.append(x)
x = x 1
腳本2:
array_2 = []
x = 0
while True:
array_2.append(x)
x = x 1
現在我想同時運行兩個行程。以前的解決方案為主腳本建議了以下代碼:
import script_1, script_2
exec(open(script_1))
exec(open(script_2))
雖然這是從另一個腳本中啟動腳本的解決方案,但是,這不會并行運行兩個腳本。這樣的主腳本實際上應該是什么樣的?
感謝您的建議!
編輯
我嘗試了以下執行緒方法:
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")
它不起作用,只有第一個函式啟動,所以我得到以下輸出:
function 1 started...
1
1
1
1
1
1
uj5u.com熱心網友回復:
當你想產生一個新執行緒時,你需要傳遞你想讓執行緒執行的函式的地址,而不是呼叫它。您在這里所做的基本上是生成一個新執行緒,function_1()該執行緒立即呼叫該執行緒當然會永遠運行。
此外,您將無法訪問這行代碼:
print("thread finished")
由于執行緒正在執行 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
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/354215.html
