change KeyboardInterrupt to 'enter'

Question:

I have the following code:

import time

def run_indefinitely():
    while True:
        # code to run indefinitely goes here
        print("Running indefinitely...")
        time.sleep(1)  

try:
    
        # Run the code indefinitely until Enter key is pressed
        run_indefinitely()            

except KeyboardInterrupt:
    print("Loop interrupted by user")

Is there a way to break out of the while loop by hitting ‘enter’ instead of ctrl+C ?

Asked By: DCR

||

Answers:

This is surprisingly tricky to do in Python.

import os
import signal
import sys
import time
from threading import Timer

from readchar import readkey  # pip install readchar

def wait_for(key, timeout):
    """wait `timeout` seconds for user to press `key`"""
    pid = os.getpid()
    sig = signal.CTRL_C_EVENT if os.name == "nt" else signal.SIGINT
    timer = Timer(timeout, lambda: os.kill(pid, sig))
    timer.start()  # spawn a worker thread to interrupt us later
    while True:
        k = readkey()
        print(f"received {k!r}")
        if k == key:
            timer.cancel()  # cancel the timer
            print("breaking")
            break

def run_indefinitely():
    while True:
        print("Running indefinitely...")
        try:
            wait_for(key="n", timeout=1)
        except KeyboardInterrupt:
            continue
        else:
            break

run_indefinitely()
print("Loop interrupted by user")
Answered By: wim

Here’s a simple way:

import time
import keyboard  

def run_indefinitely():
    while True:
        # Your code to run indefinitely goes here
        print("Running indefinitely...")
        time.sleep(1) 
        if keyboard.is_pressed('enter'):
            break


   
run_indefinitely()

        


    
print("how now brown cow")
Answered By: DCR
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.