在按键上中断循环 [英] Break loop on keypress

查看:51
本文介绍了在按键上中断循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个连续循环,它修改数组中的数据并在每个循环中暂停一秒钟.这没问题......但我还需要在输入特定按键时将数组的特定部分打印到屏幕上,而不会中断以一秒为间隔运行的连续循环.

I have a continuous loop that modifies data in an array and pauses for one second on every loop. Which is no problem..but I also need to have to print a specific part of the array to the screen on a specific keypress is entered, without interrupting the continuous loop running in one second intervals.

关于如何在不中断循环的情况下获得按键的任何想法?

Any ideas on how to get the keypress while not distrupting the loop?

推荐答案

您可以使用 multiprocessingthreading 库以生成一个新进程/线程将运行连续循环,并通过读取用户输入继续主流程(将数组的特定部分打印到屏幕等).

You can use either multiprocessing or threading library in order to spawn a new process/thread that will run the continuos loop, and continue the main flow with reading the user input (print a specific part of the array to the screen etc).

示例:

import threading

def loop():
    for i in range(3):
        print "running in a loop"
        sleep(3)
    print "success"

if __name__ == '__main__':

    t = threading.Thread(target=loop)
    t.start()
    user_input = raw_input("Please enter a value:")
    print user_input
    t.join()

这篇关于在按键上中断循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆