Python:等待时接受输入 [英] Python: Accept input while waiting

查看:418
本文介绍了Python:等待时接受输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个小脚本,每5分钟编写一次以执行任务(这不一定是准确的),但是由于它是当前编写的,因此唯一可以取消的方法是使用Ctrl + Z(Linux终端)而且没有重新启动脚本就无法更改其执行的任务集的方式.

I have a small script that I have written to perform tasks every 5 minutes (this does not need to be exact), but as it is written currently the only way it can be cancelled is with Ctrl+Z (linux terminal) and there is no way of changing what set of tasks it performs without restarting the script.

因此,我想更改脚本,以便在等待下一次运行时接受 用户输入,而不会大量中断5分钟计时器(如杀死脚本和当前重启),但是我无法弄清楚如何使raw input仅在给定时间内接受值,等等.另外,当前代码是用Python 2.7编写的,但是我很乐意转换为3,这样可以简化解决方案.

As a result, I'd like to change the script to be able to accept user input while waiting to do the next run without interrupting the 5-minute timer by any large amount (as killing the script and restarting currently does), but I can't figure out how to get raw input to accept values for only a given time, etc. Also the current code is written in Python 2.7, but I'm happy to convert to 3 if that makes the solution easier.

当前代码如下:

# Setup for the tasks
while(True):
    # Do the tasks
    for i in range(5):
        print "Next run in " + str(5-i) + " mins"
        time.sleep(60)

有什么想法吗?

更新:此问题并未导致发布特定的代码解决方案,因此,这里是

UPDATE: This question did not lead to a specific code solution being posted, so here'a a link to a later question that had a simple version of the solution I implemented (and the one simple edit that it required it to work in the answers)/

推荐答案

我认为您想要这样的东西.

I think you want something like that.

import threading

def takeInput():
    """This function will be executed via thread"""
    value = raw_input("what you want:")
    return

#initialize how you want
value = 0 
t = threading.Thread(target=takeInput)
t.start()
time.sleep(5) 

这篇关于Python:等待时接受输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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