1 回答

TA貢獻1883條經驗 獲得超3個贊
像大多數語言一樣,Python 也使用處理函數來處理系統信號。有關更多詳細信息,請查看討論接收和發送信號的信號章節,例如此處的示例。
簡而言之,您可以將一個函數綁定到一個或多個信號:
>>> import signal
>>> import sys
>>> import time
>>>
>>> # Here we define a function that we want to get called.
>>> def received_ctrl_c(signum, stack):
... print("Received Ctrl-C")
... sys.exit(0)
...
>>> # Bind the function to the standard system Ctrl-C signal.
>>> handler = signal.signal(signal.SIGINT, received_ctrl_c)
>>> handler
<built-in function default_int_handler>
>>>
>>> # Now let’s loop forever, and break out only by pressing Ctrl-C, i.e. sending the SIGINT signal to the Python process.
>>> while True:
... print("Waiting…")
... time.sleep(5)
...
Waiting…
Waiting…
Waiting…
^CReceived Ctrl-C
在您的特定情況下,找出機器人向您的 Python 進程(或任何偵聽信號的進程)發送哪些信號,然后如上所示對它們采取行動。
添加回答
舉報