Python: Accept input while waiting [duplicate]

2019-02-28 06:16发布

问题:

This question already has an answer here:

  • How to set time limit on raw_input [duplicate] 6 answers

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.

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.

The current code looks something like this:

# 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)

Any ideas?

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)/

回答1:

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)