我在一个循环中运行顺序代码,该循环正在进行各种计算,并偶尔打印出我在控制台中监视的结果。
我想做的是能够在程序运行时按下键盘按钮,然后在该循环的下一次开始迭代时保存并处理该输入(例如,作为更改某些参数的命令)。
这是我正在运行的代码的结构:
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 同时做两件事(获取用户输入和计算),最简单的方法是使用单独的线程(单独的进程更难,在这种情况下没有必要)。高级线程
库非常容易上手,我建议浏览一下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
关于Python在循环执行其他代码时捕获用户输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41643538/