nohup 命令允許你在后臺運行程序,即使你關閉了終端
timeout 命令:你可以使用 timeout 命令來限制 Python 腳本的執行時間。首先,確保你的系統已經安裝了 coreutils(在大多數 Linux 發行版中默認已安裝)。然后,你可以使用以下命令:
timeout 30s python your_script.py
這將限制 your_script.py 的執行時間為 30 秒。如果腳本在 30 秒內未完成,timeout 將終止它。
你還可以使用信號處理來設置 Python 腳本的超時時間。在你的 Python 腳本中,你可以捕獲 SIGTERM 信號并在接收到信號時執行清理操作。例如:
import signal
import sys
def signal_handler(sig, frame):
print('Timeout reached, terminating the script.')
sys.exit(0)
signal.signal(signal.SIGTERM, signal_handler)
# Your script code here
然后,你可以使用 kill 命令發送 SIGTERM 信號到你的 Python 進程:
python your_script.py &
pid=$!
# Replace 10 with the desired timeout in seconds
timeout 10s kill -SIGTERM $pid
這將限制 your_script.py 的執行時間為 10 秒。如果腳本在 10 秒內未完成,kill 命令將發送 SIGTERM 信號,終止它。