如何检查在python中运行程序时是否按下了按钮
我想在Python中运行一个程序,同时检查整个时间是否按下了按钮(物理类型)。该程序如下所示:如何检查在python中运行程序时是否按下了按钮,python,python-3.x,python-multithreading,Python,Python 3.x,Python Multithreading,我想在Python中运行一个程序,同时检查整个时间是否按下了按钮(物理类型)。该程序如下所示: import stuff a = True def main(): important stuff which takes about 10 seconds to complete while True: if a == True: main() #at the same time as runni
import stuff
a = True
def main():
important stuff which takes about 10 seconds to complete
while True:
if a == True:
main()
#at the same time as running main(), I also want to check if a button
#has been pressed. If so I want to set a to False
我可以在main完成后检查按钮是否被按下,但这意味着当python检查按钮是否被按下(或按住按钮)时,我必须在瞬间按下按钮
如何让python在运行main()时检查按钮是否被按下?以下是一些您可以尝试的方法。
main
功能每秒打印一个数字,您可以通过键入“s”+回车键来中断它:
import threading
import time
a = True
def main():
for i in range(10):
if a:
time.sleep(1)
print(i)
def interrupt():
global a # otherwise you can only read, and not modify "a" value globally
if input("You can type 's' to stop :") == "s":
print("interrupt !")
a = False
t1 = threading.Thread(target=main)
t1.start()
interrupt()
它只监视按钮是否被按下。当按下按钮时,让它设置一个标志,当“main”线程决定是否再次运行
main()
时,它会查看该标志。该建议似乎不起作用(除了“(target=main)”实际上应该是“(target=main())——在倒数第二行)。中断()函数仅在main()完成后调用。我在输入中添加了一条消息:“您可以键入's'停止:”。通过这种方式,您可以看到interrupt
函数在main
启动的同时被调用。并且不要将target=main
替换为target=main()
,否则它将不会作为线程工作…只有在所有数字(0-9)出现后才会显示“您可以键入”停止“消息。在运行实际程序时,还会出现以下错误:文件“/usr/lib/python3.7/threading.py”,第781行,在init assert group is None中,“group参数现在必须为None”AssertionError:group参数现在必须为None可能需要安装libpip install threading