首页 > 解决方案 > 使用线程等待类变量更改

问题描述

我尝试了以下代码片段。它存在于两个单独的.py文件中ChrMain.pyxlWingsTest.py 意思是在主代码中等待,直到excel触发类值为True。该代码没有给出任何错误,但它不会触发主代码。我不喜欢在代码中使用 sleep 。当 excel 和 xlWings 执行触发器时,主代码已经在运行。

主要代码

from waiting import wait as Wait
import time
import threading

class RunSub:
    RunNu = False

class RunMain:
    isRun = True

def ChrMain():
    while RunMain.isRun:
        try:
            print('Sub is waiting')
            Wait(lambda : RunSub.RunNu, timeout_seconds = 40)
            print('Sub is continueing ...')
            # Do other Stuff
            time.sleep(5) # This line is only for testing
            RunMain.isRun = False
        except:
            pass

m = threading.Thread(name = 'Main', target = ChrMain())
m.start()
print('Program End')
exit()


***Trigger Code***


import xlwings as xw

def SetRunNow(myBool):
    if myBool:
        RunSub.RunNu  = True
    else:
        RunSub.RunNu = False

def StopProg(myBool):
    if myBool:
        RunMain.isRun = True
    else:
        RunMain.isRun = False

@xw.func
def Injector(myBool, strfunctie):
    import threading
    if strfunctie == 'SetRunNow':
        from ChrMain import RunSub
        i = threading.Thread(name = 'RunNow', target = SetRunNow(myBool))
        i.start()
        i.join()
        return RunSub.RunNu
    elif strfunctie == 'StopProg':
        from ChrMain import RunMain
        i = threading.Thread(name = 'StopProg', target = StopProg(myBool))
        i.start()
        i.join()
        return RunMain.isRun
    #exit()




标签: pythonmultithreadingmultiprocessingwait

解决方案


此行可能有错误:i = threading.Thread(name = 'RunNow', target = SetRunNow(myBool))

target必须是函数,但是SetRunNow(myBool)是布尔值。解决此问题的方法是:

i = threading.Thread(name = 'RunNow', target = lambda: SetRunNow(myBool))


推荐阅读