python - 使用线程等待类变量更改
问题描述
我尝试了以下代码片段。它存在于两个单独的.py
文件中ChrMain.py
,xlWingsTest.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()
解决方案
此行可能有错误:i = threading.Thread(name = 'RunNow', target = SetRunNow(myBool))
target
必须是函数,但是SetRunNow(myBool)
是布尔值。解决此问题的方法是:
i = threading.Thread(name = 'RunNow', target = lambda: SetRunNow(myBool))
推荐阅读
- c - 为什么需要浮动功能
- javascript - 如何从一个 NPM 包中导出多个 ES6 模块
- whois - Rdap 查询的结果比 google.com 的 whois 少?
- jquery - 在 Laravel 中获取 http://localhost:8888/appraisal/appraisal_goals/findScore?id=2 404(未找到)
- python - 自定义处理程序中的 Django 参数数量错误
- ruby-on-rails - 在活动管理员的导航链接中禁用用户名
- python - 如何从 Telegram 获取公共频道的消息
- javascript - 将数组对象转换为对象对象
- mysql - MySQL 根据时间范围选择
- google-cloud-platform - 是否有一个选项可以控制 GCP Autoscaling 中最新实例是终止还是旧实例