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 信号,终止它。