Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/331.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 - Fatal编程技术网

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

Python在循环中执行其他代码时捕获用户输入?,python,Python,我在一个循环中运行顺序代码,循环中执行各种计算,偶尔打印出我在控制台中监视的结果 我想做的是在程序运行时点击键盘按钮,然后在循环的下一次开始迭代中保存和处理输入(例如,作为更改某些参数的命令) 下面是我正在运行的代码的结构: for i in range(0, itrs): # ideally at the start of each loop: # check to see if user pressed keybutton during prev loop itr,

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

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

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

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可能有更简单的解决方案。

使用线程运行
doSequentialComputing
函数,并将
param
作为线程参数传递给它:

import threading
t = threading.Thread(target=doSequentialComputation, args=(param,))
t.daemon = True
t.start()
主线程中对
param
的任何修改都将被线程中的代码看到。确保使用
线程锁来保护对
参数的访问

param_lock = threading.Lock()
userKeyInput = checkIfUserPressedKey()
with param_lock:
    parm = modify(userKeyInput)
总而言之:

import threading

class Parameter(object):
    pass

def doSequentialComputation(param, param_lock):
    itrs = 1000
    param_copy = None
    with param.lock:
        param_copy = param
    for i in range(0, itrs)
        with param.lock:
            if param.has_changed:
                param_copy = param
                param.has_changed = False
        compute(param_copy)

def main():
    param = Parameter()
    param.has_changed = False
    param.lock = threading.Lock()
    args=(param, param_lock)
    compute_thread = threading.Thread(target=doSequentialComputation, args=args)
    compute_thread.daemon = True
    compute_thread.start()
    while True:
        userKeyInput = checkIfUserPressedKey()
        with param.lock:
            param = modify(userKeyInput, param)
            param.has_changed = True

参数
类允许我们创建一个可以添加任意属性的对象。

如果您想让python同时做两件事(获取用户输入和计算),最简单的方法是使用单独的线程(在本例中,单独的进程更难,也不需要)。高级
线程
库非常容易开始使用,我建议重新使用,但这里有一个快速示例:

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

您需要一个线程在internet上运行parallellook for
getch()
-这不是标准命令,可能无法与某些控制台一起使用。可能的重复:@furas我不认为这与获取角色有关。。。我想他需要知道如何让它同时工作。@Aaron
getch()
不会阻止代码-它不会等待键-所以你可以在循环中使用它,同时做其他事情
,因为范围内的I(0,itrs)
似乎需要
,即范围内的I(0,itrs):