0

I have a small script where I have a continuous loop. The loop runs and I expect that the user will give an input whenever he wants. I want to check if the user wrote something in the console, if yes, I will do something extra, if not, the loop continues. The problem is that when I call the input() function, the program waits for user input.

The code that I will use here will be just a simple version of my code to show better what is my problem.

i=0
while True:
    i+=1
    if 'user wrote a number':
        i+= 'user's input'

The objective is to not stop the loop if the user do not input anything. I believe this is a simple thing but I didn't find an answer for this problem.

Thank you for your time!

  • The other option is to listen for key strokes: https://stackoverflow.com/questions/24072790/detect-key-press-in-python – Mike67 Oct 28 '20 at 19:14
  • maybe try running functions in parallel – Matiiss Oct 28 '20 at 19:15
  • https://stackoverflow.com/questions/2408560/python-nonblocking-console-input – Amin Gheibi Oct 28 '20 at 19:17
  • @AminGheibi That is overly complicated and I believe only works for single-char keystrokes. It should be possible to achieve this by running `input()` on a separate thread (or possible easier, the "background loop"). – DeepSpace Oct 28 '20 at 19:20

2 Answers2

2

You can execute the background task (the while True) on a separate thread, and let the main thread handle the input.

import time
import threading
import sys

def background():
    while True:
        time.sleep(3)
        print('background task')

def handling_input(inp):
    print('Got {}'.format(inp))

t = threading.Thread(target=background)
t.daemon = True
t.start()

while True:
    inp = input()
    handling_input(inp)
    if inp == 'q':
        print('quitting')
        sys.exit()

Sample execution (lines starting with >> are my inputs):

background task
>> a
Got a
>> b
Got b
background task
>> cc
Got cc
background task
background task
>> q
Got q
quitting

Process finished with exit code 0

The only caveat is if the user takes longer than 3 seconds to type (or whatever the value of time.sleep in background is) the input value will be truncated.

DeepSpace
  • 78,697
  • 11
  • 109
  • 154
-1

I'm don't think you can do that in one single process input(), because Python is a synchronous programming languaje,the execution will be stoped until input() receives a value.

As a final solution I'd recommend you to try implement your functions with parallel processing so that both 'functions' (input and loop) can get executed at the same time, then when the input function gets it's results, it sends the result to the other process (the loop) and finish the execution.

Stack
  • 1,028
  • 2
  • 10
  • 31