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?

Skysmithio
  • 91
  • 1
  • 4
  • 1
    What is your question? – DYZ Jan 15 '18 at 21:41
  • 2
    Should `function_to_run_in_background` run only once (with a delay of 2 seconds) or once every 2 seconds? – Aran-Fey Jan 15 '18 at 21:43
  • As per my edit for clarification I would like `function_to_run_in_background` to run once every 2 seconds. – Skysmithio Jan 15 '18 at 23:54
  • `Timer` only runs once (after 2 seconds in your case), as per the documentation. –  Jan 16 '18 at 00: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.) –  Jan 16 '18 at 00:10
  • I have updated the question with what I was thinking so far. It does print "HI" every 2 seconds, but it does not seem to return to the main thread at all because when I type quit into the command it does not actually end the program. My guess is it is stuck in the `function_to_run_in_background` side of things. Any idea why this might be? Will be looking into `sched.scheduler` next as that sounds promising. – Skysmithio Jan 16 '18 at 02:18

1 Answers1

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'`
Skysmithio
  • 91
  • 1
  • 4