[英]Running multiple Python Scripts from one file
我有3個需要執行的腳本。 它們中的兩個具有連續循環,只要傳感器發送數據就不會停止運行,並且第3個腳本每小時僅運行一次。
所以可以說我有這樣的他們:
sensorscript1 sensorscript2導出
創建一個文件來運行此過程的最佳方法是什么? 在這種情況下,使用線程將是最好的方法嗎?
import sensorscript1, sensorscript2
from threading import Thread
還是Flask應用程序更適合於此? 還有其他建議嗎?
如果您希望每個腳本在新窗口中運行並查看其日志,則還有另一種方法。
您可以運行一個使用subprocess
調用來調用其他腳本的腳本。
import subprocess
subprocess.call("start cmd /K python sensorscript1.py", shell=True)
# this opens the script1.py file in a new console window (shell=True)
subprocess.call("start cmd /K python sensorscript2.py", shell=True)
subprocess.call("start cmd /K python Export.py", shell=True)
或者,您也可以運行Export並從中調用其他兩個腳本-由您自行決定如何最好地運行它。
使用PyThreads,這是python的新線程庫。 https://github.com/Narasimha1997/PyThreads ,這使運行線程更加容易。
例如,您有3個腳本文件f1,f2和f3,使用PyThreads將所有這3個文件中的函數寫為線程
示例:文件-1
from pythreads import pythread
@pythread
def fun1() :
#some logic
pass
文件-2:
from pythreads import pythread
@pythread
def fun2():
#some logic
pass
現在在主文件中導入它們
from file1 import fun1
from file2 import fun2
#call these functions, because of @pythreads, they start behaving like threads
fun1()
fun2()
#your function 3
def fun3():
#some logic
pass
#call it here
if __name__ == "__main__" :
fun3()
PS:我編寫了PyThreads來簡化python中的線程使用
你差不多了
import sensorscript1, sensorscript2
from threading import Thread
t1 = Thread(target=sensorscript1, args=(arg1, arg2))
t2 = Thread(target=sensorscript2, args=(arg,))
t1.run()
t2.run()
請注意,僅在將參數傳遞給函數時才需要args參數。 另請注意多余的逗號。 這是因為args參數需要一個元組
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.