Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/290.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何检查在python中运行程序时是否按下了按钮_Python_Python 3.x_Python Multithreading - Fatal编程技术网

如何检查在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

我想在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 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可能需要安装lib
pip install threading