Processing a key pressed in Python 3.6

Chris Angelico rosuav at gmail.com
Tue Jan 23 14:15:41 EST 2018


On Wed, Jan 24, 2018 at 5:50 AM, Virgil Stokes <vs at it.uu.se> wrote:
> I would appreciate help on finding a solution to following problem. This is
> the general structure of the "problem" code:
>
>> while True
>>     # Get some data from the web and process it
>>     ...
>>     ...
>>     # Write these data to a file
>>     ...
>>     ...
>>     # Check if a_key has been pressed in the command window
>>     ...
>>     ...
>>     if a_key_pressed:
>>         # Perform some pre-termination tasks
>>         ...
>>         ...
>>         # Close the output data file
>>         ...
>>         ...
>>         raise SystemExit('Exit')
>
>
> I am running the code with Python 3.6 on a windows 10 platform. I have tried
> many approaches (mainly those posted on stackoverflow) but I have yet to
> find an approach that works for this structure.
>
> Note:
>   1) The code is executed in the windows 10 command window
>   2) I am not using wxPython, IDLE, or pyGame in this application.
>   3) The time to get the data, process it and write it to a file can
>      take from 0.5 sec to 1.5 sec
>   4) The key hit need not be echoed to the command window
>

Are you okay with demanding a specific key, rather than simply "press
any key"? Even better, key combination? Handle Ctrl-C by catching
KeyboardInterrupt and you can take advantage of Python's existing
cross-platform handling of the standard interrupt signal.

If Ctrl-C won't work for you, how about stipulating that it be Enter?
"Press Enter to quit" isn't too much worse than "Press any key to
quit" (plus you have less chance of accidentally terminating the
program when you don't want to). Spin off a thread to wait for enter.
I've tested this only on Linux, but it ought to work:

import threading
import time

shutdown = False
def wait_for_enter():
    print("Hit Enter to quit.")
    input()
    global shutdown; shutdown = True

threading.Thread(target=wait_for_enter).start()

while "more work to do":
    print("Getting data...")
    time.sleep(1)
    print("Saving data to file...")
    time.sleep(1)
    if shutdown:
        print("Pre-termination...")
        time.sleep(1)
        raise SystemExit("exit")

If it doesn't, try switching around which is the secondary thread and
which is the primary - spin off a thread to do the work, then call
input() in the main thread.

ChrisA



More information about the Python-list mailing list