我第一次用 python 尝试信号,我创建了一些基本脚本,但似乎无法正确执行。有人可以解释一下我在哪里犯了错误吗?
import signal
import sys
def signal_abort_script(signal, frame):
"""
Signal handler function to catch KeyboardInterrupt (Ctrl+C) and exit the script gracefully.
"""
sys.exit()
def main():
# Set up the signal handler to catch KeyboardInterrupt (Ctrl+C)
signal.signal(signal.SIGINT, signal_abort_script)
# print not stopped forever
while True:
print("not stopped forever")
if __name__ == "__main__":
main()
好吧,与此同时,在 chatgpt 的帮助下,我得到了我想要实现的目标。现在我可以启动和停止脚本了。
import threading
import time
from pynput.keyboard import Listener, KeyCode
startStopButton = KeyCode(char='s')
terminateButton = KeyCode(char='\x03')
running = False
program_running = True
def start():
global running
running = True
def stop():
global running
running = False
def exit_script():
global running, program_running
running = False
program_running = False
def print_hi():
while program_running:
if running:
print("hi")
time.sleep(1) # Adjust the delay as needed
def on_press(key):
if key == startStopButton:
if running:
stop()
else:
start()
elif key == terminateButton:
exit_script()
listener.stop()
print("Press 's' to start, 'ctrl+c' to exit.")
print_hi_thread = threading.Thread(target=print_hi)
print_hi_thread.start()
with Listener(on_press=on_press) as listener:
listener.join()
仅包含睡眠和打印语句以查看结果
结果还好
$ winpty python test.py
not stopped forever
not stopped forever
pressed ctrl C
import signal
import sys
import time
def signal_abort_script(signal, frame):
"""
Signal handler function to catch KeyboardInterrupt (Ctrl+C) and exit the script gracefully.
"""
print("pressed ctrl C")
sys.exit()
def main():
# Set up the signal handler to catch KeyboardInterrupt (Ctrl+C)
signal.signal(signal.SIGINT, signal_abort_script)
# print not stopped forever
while True:
time.sleep(1)
print("not stopped forever")
if __name__ == "__main__":
main()