signal to stop script in python

huangapple go评论58阅读模式
英文:

signal to stop script in python

问题

我正在尝试使用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():
    # 设置信号处理程序以捕获 KeyboardInterrupt (Ctrl+C)
    signal.signal(signal.SIGINT, signal_abort_script)

    # 持续打印"not stopped forever"
    while True:
        print("not stopped forever")


if __name__ == "__main__":
    main()
英文:

i am trying out signals for the first time with python and i created some basic script that just cant seem to get it right. Can somebody explain where im making the mistake?

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()

答案1

得分: 1

只是加了一个睡眠和打印语句来查看结果

结果还可以

$ winpty python test.py
永远不会停止
永远不会停止
按下Ctrl+C
import signal
import sys
import time


def signal_abort_script(signal, frame):
    """
    信号处理函数,用于捕获KeyboardInterrupt(Ctrl+C)并优雅地退出脚本。
    """
    print("按下Ctrl+C")
    sys.exit()


def main():
    # 设置信号处理程序以捕获KeyboardInterrupt(Ctrl+C)
    signal.signal(signal.SIGINT, signal_abort_script)

    # 打印永远不会停止
    while True:
        time.sleep(1)
        print("永远不会停止")


if __name__ == "__main__":
    main()
英文:

just included the sleep and a print statement to just see the result

result was ok

$ 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()


答案2

得分: 0

好的,以下是代码的翻译:

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)  # 根据需要调整延迟


def on_press(key):
    if key == startStopButton:
        if running:
            stop()
        else:
            start()
    elif key == terminateButton:
        exit_script()
        listener.stop()


print("按下 's' 键开始,按下 'ctrl+c' 退出。")
print_hi_thread = threading.Thread(target=print_hi)
print_hi_thread.start()

with Listener(on_press=on_press) as listener:
    listener.join()

希望对你有帮助!

英文:

okay in the meantime i got what i wanted to achieve with a bit of help of chatgpt. Now i can start and stop the script.

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()

huangapple
  • 本文由 发表于 2023年8月9日 04:04:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/76862889.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定