3

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.

4
  • 1
    how do you plan to interrupt the "pause"? Commented Jun 30, 2019 at 1:49
  • 3
    I strongly suspect you're not explaining what you want to accomplish clearly. Anyway, here's one guess, see Non-Blocking raw_input() in python. Commented Jun 30, 2019 at 2:23
  • 1
    @DavidZemens you are right, you can't do it in the same thread! So I created two, one for the loop another for the interrupt Commented Jun 30, 2019 at 2:28
  • @martineau that would be another great approach! thanks for sharing Commented Jun 30, 2019 at 2:34

2 Answers 2

4

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

Comments

1

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

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.