Reputation: 91
I want to write a python command line script that will accept user input while simultaneously running another function or script at constant intervals. I have written some pseudo-code below to show what I am aiming for:
def main():
threading.Timer(1.0, function_to_run_in_background).start()
while True:
command = raw_input("Enter a command >>")
if command.lower() == "quit":
break
def function_to_run_in_background():
while True:
print "HI"
time.sleep(2.0)
if __name__ == "__main__":
main()
I have tried to make something along these lines work, but usually what happens is that the function_to_run_in_background only runs once and I would like it to run continuously at a specified interval while the main thread of the program accepts user input. Is this close to what I am thinking of or is there a better way?
Upvotes: 3
Views: 3060
Reputation: 91
Below is essentially what I was looking for. It was helped along by @Evert as well as the answer located here How to use threading to get user input realtime while main still running in python:
import threading
import time
import sys
def background():
while True:
time.sleep(3)
print 'disarm me by typing disarm'
def save_state():
print 'Saving current state...\nQuitting Plutus. Goodbye!'
# now threading1 runs regardless of user input
threading1 = threading.Thread(target=background)
threading1.daemon = True
threading1.start()
while True:
if raw_input().lower() == 'quit':
save_state()
sys.exit()
else:
print 'not disarmed'`
Upvotes: 2