Python pause loop on user input

Question:

Hey I am trying to have a loop be pausable from user input like having a input box in the terminal that if you type pause it will pause the loop and then if you type start it will start again.

while True:
    #Do something
    pause = input('Pause or play:')
    if pause == 'Pause':
        #Paused

Something like this but having the #Do something continually happening without waiting for the input to be sent.

Asked By: Gus

||

Answers:

Ok I get it now, here is a solution with Threads:

from threading import Thread
import time
paused = "play"
def loop():
  global paused
  while not (paused == "pause"):
    print("do some")
    time.sleep(3)

def interrupt():
  global paused
  paused = input('pause or play:')


if __name__ == "__main__":
  thread2 = Thread(target = interrupt, args = [])
  thread = Thread(target = loop, args = [])
  thread.start()
  thread2.start()
Answered By: developer_hatch

You can’t directly, as input blocks everything until it returns.
The _thread module, though, can help you with that:

import _thread

def input_thread(checker):
    while True:
        text = input()
        if text == 'Pause':
            checker.append(True)
            break
        else:
            print('Unknown input: "{}"'.format(text))

def do_stuff():
    checker = []
    _thread.start_new_thread(input_thread, (checker,))
    counter = 0
    while not checker:
        counter += 1
    return counter

print(do_stuff())
Answered By: musicamante
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.