不断地 运行 python 脚本
constantly run python script
我有一个 python 脚本,可以在网站发生变化时向我发送短信。我怎样才能把它放在服务器上,这样它就可以 24/7 全天候检查,而不必让我的笔记本电脑保持打开状态?任何教程或文档都会很好。
我到处都在寻找这样做的方法,但真的找不到太多。我看到 php 可以用来做到这一点,但我不确定这是否是最好的方法。
您需要设置一个 cron 作业。 "Cron" 是一个基于时间的作业调度程序。
例如:
11 2 * * * /path/to/bin/python /path/to/cronjobs/sent_text.py
此 Cron 将 运行 每小时一次
您需要 运行 您的 python 脚本作为守护进程。那就是将它从控制终端中分离出来。您可以轻松地将其包装在 shell 脚本中,如下所示。
#!/usr/bin/env bash
script_file=$(readlink -f "[=10=]") #absolute path to this file
python_file=$(readlink -f "") #absolute path to the python script
output_file=$([[ "" == "" ]] && echo "/dev/null" || readlink -f "") #absolute path to the output file
(
exec 0>&- 0>/dev/null #close and redirect stdin
exec 1>&- 1>>"${output_file}" #close and redirect stdout
exec 2>&- 2>>"${output_file}" #close and redirect stderr
python "$python_file"
"$script_file" "$python_file" "$output_file"
) &
将此脚本保存为 script.sh
并赋予它可执行权限,即 chmod +x script.sh
现在执行 script.sh <python script> <output file>
将启动 python 脚本,并将 stdout 和 stderr 重定向到输出给的文件。如果 python 脚本终止,它也会重新启动。
我有一个 python 脚本,可以在网站发生变化时向我发送短信。我怎样才能把它放在服务器上,这样它就可以 24/7 全天候检查,而不必让我的笔记本电脑保持打开状态?任何教程或文档都会很好。
我到处都在寻找这样做的方法,但真的找不到太多。我看到 php 可以用来做到这一点,但我不确定这是否是最好的方法。
您需要设置一个 cron 作业。 "Cron" 是一个基于时间的作业调度程序。
例如:
11 2 * * * /path/to/bin/python /path/to/cronjobs/sent_text.py
此 Cron 将 运行 每小时一次
您需要 运行 您的 python 脚本作为守护进程。那就是将它从控制终端中分离出来。您可以轻松地将其包装在 shell 脚本中,如下所示。
#!/usr/bin/env bash
script_file=$(readlink -f "[=10=]") #absolute path to this file
python_file=$(readlink -f "") #absolute path to the python script
output_file=$([[ "" == "" ]] && echo "/dev/null" || readlink -f "") #absolute path to the output file
(
exec 0>&- 0>/dev/null #close and redirect stdin
exec 1>&- 1>>"${output_file}" #close and redirect stdout
exec 2>&- 2>>"${output_file}" #close and redirect stderr
python "$python_file"
"$script_file" "$python_file" "$output_file"
) &
将此脚本保存为 script.sh
并赋予它可执行权限,即 chmod +x script.sh
现在执行 script.sh <python script> <output file>
将启动 python 脚本,并将 stdout 和 stderr 重定向到输出给的文件。如果 python 脚本终止,它也会重新启动。