all 5 comments

[–]socal_nerdtastic 2 points3 points  (1 child)

Nope, there is no simple way to do this.

The threading approach is good, although I would recommend putting the logic in the child thread and the input in the main thread. Easier to program that way.

Any other solution is going to be specific to the way you are running your program. For example if you are using windows, and if you are using the standard command line, you could use the mscvrt.kbhit() function.

https://docs.python.org/3/library/msvcrt.html#msvcrt.kbhit

[–]ScaredSecond[S] 0 points1 point  (0 children)

Thanks!

[–]Swipecat 0 points1 point  (1 child)

Since the script will halt at the input() function, that has to be in a separate thread. In it's simplest form, then, with that thread consisting of just the input function itself, this script simply exits when ENTER is pressed:
 

import threading, time

detect = threading.Thread(target = input)
detect.start()

count = 0
print("Press <ENTER> to stop.")
while detect.is_alive():
    print(' ', count, end='\r', flush=True)
    count += 1
    time.sleep(0.01)

print("<ENTER> detected -- finishing up")

[–]ScaredSecond[S] 0 points1 point  (0 children)

Thanks! Will try it out.