3

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?

6
  • 1
    What is your question? Commented Jan 15, 2018 at 21:41
  • 2
    Should function_to_run_in_background run only once (with a delay of 2 seconds) or once every 2 seconds? Commented Jan 15, 2018 at 21:43
  • As per my edit for clarification I would like function_to_run_in_background to run once every 2 seconds. Commented Jan 15, 2018 at 23:54
  • Timer only runs once (after 2 seconds in your case), as per the documentation. Commented Jan 16, 2018 at 0:09
  • A simple alternative is to create a thread (without a timer) that runs an infinite while loop itself, with a sleep function. That won't run your function exactly every 2 seconds, since the function itself takes time, but it may get close to what you want. (sched.scheduler may help.) Commented Jan 16, 2018 at 0:10

1 Answer 1

2

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'`
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.