Python 当函数位于另一个模块中时,线程无法正常工作
我目前正在使用Python中的守护进程线程在后台不断检测屏幕的某些部分,同时运行其他更重要的函数Python 当函数位于另一个模块中时,线程无法正常工作,python,multithreading,python-multithreading,Python,Multithreading,Python Multithreading,我目前正在使用Python中的守护进程线程在后台不断检测屏幕的某些部分,同时运行其他更重要的函数testimtost与我正在使用的其余代码位于同一个文件中 def testImToStr(): while True: pospro.imagetoString(); doImageToString = threading.Thread(target=testImToStr, args=(), daemon=True) doImageT
testimtost
与我正在使用的其余代码位于同一个文件中
def testImToStr():
while True:
pospro.imagetoString();
doImageToString = threading.Thread(target=testImToStr, args=(), daemon=True)
doImageToString.start()
while True:
#other stuff i was too lazy to copy over
这个版本的工作原理是图像处理和while循环中的其他工作。
但是,目标线程位于另一个模块中:
doImageToString = threading.Thread(target=pospro.loopedImToStr, args=(), daemon=True)
doImageToString.start()
while True:
#other stuff i was too lazy to copy over
def loopedImToStr():
while True:
imagetoString()
def imagetoString():
#stuff here
其他模块:
doImageToString = threading.Thread(target=pospro.loopedImToStr, args=(), daemon=True)
doImageToString.start()
while True:
#other stuff i was too lazy to copy over
def loopedImToStr():
while True:
imagetoString()
def imagetoString():
#stuff here
它只循环目标线程,不在最初生成线程的文件中运行while循环。当线程与循环在同一个文件中时,两个循环如何运行,而当它们在不同的文件中时,只有线程运行?我认为您所有的问题都会犯一个最常见的错误-
目标必须是没有()
的函数名-所谓的回调
Thread(target=pospro.loopedImToStr, daemon=True)
稍后Thread.start()
将使用()
运行它
在您的代码中,您可以像
result = testImToStr()
doImageToString = threading.Thread(target=result, ...)
因此,testimtost()
阻塞了所有代码,它不能运行其他循环。最常见的错误-target
必须是没有()
的函数名(所谓的callback
)-target=pospro.loopedImToStr
,稍后线程将使用()
运行它。