Created
December 7, 2024 16:34
-
-
Save iTrooz/a47ae5e07665309f549deb26113f3439 to your computer and use it in GitHub Desktop.
Allows you to always use Ctrl+C on a command
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
""" | |
Allows you to always use Ctrl+C on a command | |
2 Ctrl+C = SIGTERM | |
3 Ctrl+C = SIGKILL | |
""" | |
import signal | |
import sys | |
import datetime | |
import subprocess | |
if len(sys.argv) < 2: | |
print("Usage: alwaysctrlc <command> [args]") | |
sys.exit(1) | |
command = sys.argv[1:] | |
process = subprocess.Popen(command) | |
last_ctrlc_time = datetime.datetime.now() | |
ctrlc_count = 0 | |
def signal_handler(sig, frame): | |
global last_ctrlc_time, ctrlc_count | |
# Reset the counter if the last Ctrl+C was more than 1 second ago | |
if datetime.datetime.now() - last_ctrlc_time > datetime.timedelta(seconds=1): | |
ctrlc_count = 0 | |
ctrlc_count += 1 | |
last_ctrlc_time = datetime.datetime.now() | |
if ctrlc_count == 2: | |
print('AlwaysCTRLC: Sending SIGTERM to the process') | |
process.send_signal(signal.SIGTERM) | |
elif ctrlc_count >= 3: | |
print('AlwaysCTRLC: Sending SIGKILL to the process') | |
process.send_signal(signal.SIGKILL) | |
signal.signal(signal.SIGINT, signal_handler) | |
# Hang until the process finishes | |
process.wait() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment