Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PYTHON

how to catch ctrl c in python

import signal
import time
import readchar
 
def handler(signum, frame):
    msg = "Ctrl-c was pressed. Do you really want to exit? y/n "
    print(msg, end="", flush=True)
    res = readchar.readchar()
    if res == 'y':
        print("")
        exit(1)
    else:
        print("", end="
", flush=True)
        print(" " * len(msg), end="", flush=True) # clear the printed line
        print("    ", end="
", flush=True)
 
 
signal.signal(signal.SIGINT, handler)
 
count = 0
while True:
    print(f"{count}", end="
", flush=True)
    count += 1
    time.sleep(0.1)
Source by code-maven.com #
 
PREVIOUS NEXT
Tagged: #catch #ctrl #python
ADD COMMENT
Topic
Name
9+6 =