[英](Multithreading-Python) How I can create a script that run two scripts which I usually run from two different terminals?
我有兩個腳本a.py
和b.py
,它們通過本地主機(mqtt)相互發送數據,它們都依賴於配置文件conf.jso
。 我通常在兩個不同的終端執行它們,
一切都很好。 我現在正在嘗試創建另一個腳本c.py
應該執行以下操作:
config.json
a.py
和b.py
a.py
, b.py
並使用新參數重新開始現在,我對此非常陌生,所以我嘗試使用線程中的線程
from threading import Thread
for parameter in parameter
#update config.json
class exp(Thread):
def __init__(self, name):
Thread.__init__(self)
self.name = name
def run(self):
if self.name == 0:
a.runs()
else:
b.runs()
thread1 = exp(0)
thread1.start()
thread2 = exp(1)
thread2.start()
a.py 和 b.py 腳本都以:
def runs():
#whatever runs do
if __name__ = 'main':
runs()
它運行沒有錯誤,但它不起作用。 我很確定應該有一個很好的標准解決方案來解決這個問題。 有任何想法嗎? 謝謝!
您可能需要multiprocessing
,而不是threading
庫(查找multiprocessing.Process
。另一個相當等效的選項是使用subprocess.call
通過 shell 啟動兩個腳本。
關於線程 - 請記住,由於CPython
中的全局解釋器鎖,它們受到限制 - 這是流行的 python 實現,也是您可能正在使用的實現。
所以我最終找到了這個(骯臟的)解決方案......有什么改進建議嗎?
p = subprocess.Popen(['python', 'random.py']) #initialize a random process just to make sense of the firsts terminate calls in the for cycle.
for parameter in parameters
subprocess.Popen.terminate(p)
#random code
p = subprocess.Popen(['python', 'a.py'])
p = subprocess.call(['python', 'b.py'])
#here I would like to do
#subprocess.Popen.terminate(p)....but it does not work, so I putted the terminate process at the start of the for cycle
我不完全理解我寫的內容,但它工作正常。 感謝大家之前的提示,我希望進一步的解釋。
您可以使用 qt 線程。 Qt 有一個非常強大的庫,正是為此目的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.