Skip to main content
 首页 » 编程设计

Python 在循环执行其他代码时捕获用户输入

2024年10月17日7pengyingh

我在执行各种计算的循环中运行顺序代码,偶尔打印出我在控制台中监控的结果。

我想做的是能够在程序运行时按下键盘按钮,然后在该循​​环的下一次开始迭代时保存并处理该输入(例如,作为更改某些参数的命令)。

这是我正在运行的代码的结构:

for i in range(0, itrs): 
    # ideally at the start of each loop:  
    # check to see if user pressed keybutton during prev loop itr,  
    # but don't wait / poll for it!  
 
    # userKeyInput = checkIfUserPressedKey() 
    # param = modify(userKeyInput) 
 
    doSequentialComputation(param) 

解决方案是否涉及线程或中断的概念?我可能想出一个涉及文件 I/O 的解决方案,这不会很糟糕,但我在想也许 Python 有一些更简单的东西可以工作。

请您参考如下方法:

如果您希望 Python 同时做两件事(获取用户输入和计算),最简单的做法是使用单独的线程(单独的进程更难,在这种情况下没有必要)。高级 threading 库很容易上手,我建议看一下 docs ,但这是一个简单的例子:

from threading import Thread,Lock 
import time 
 
class globalVars(): 
    pass 
 
G = globalVars() #empty object to pass around global state 
G.lock = Lock() #not really necessary in this case, but useful none the less 
G.value = 0 
G.kill = False 
 
def foo(n): #function doing intense computation 
    for i in range(n): 
        if G.kill: 
            G.kill = False 
            return 
        time.sleep(n) #super intense computation 
        with G.lock: 
            G.value += i 
 
t = Thread(target=foo, args=(10,)) 
t.start() 
 
def askinput(): 
    #change to raw_input for python 2.7 
    choice = input("1: get G.value\n2: get t.isAlive()\n3: kill thread\nelse: exit\ninput: ") 
    if choice == "1": 
        with G.lock: 
            print(G.value) 
    elif choice == "2": 
        print(t.is_alive()) 
    elif choice == "3": 
        G.kill = True 
    else: 
        return 0 
    return 1 
 
while askinput(): 
    pass