编写每 5 分钟执行一次的 python 脚本 [英] write python script that is executed every 5 minutes

查看:142
本文介绍了编写每 5 分钟执行一次的 python 脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要编写一个在启动时自动启动并在树莓派上每 5 分钟执行一次的 Python 脚本.如何才能做到这一点?特别是,我如何避免脚本锁定 CPU 运行 infine 循环等待 5 分钟结束?

I need to write a python script that autostarts on boot and is executed every 5 minutes on a raspberry pi. How can this be done? in particular, how can I avoid having a script locking up the cpu running a infine loop waiting for the 5 minutes to be over?

推荐答案

您可以轻松使用 cron 用于此任务(计划运行 Python 脚本).;)

You can easily use cron for this task (schedule to run Python script). ;)

我想你已经安装了cron;如果没有,则安装一些(例如vixie-cron).

I suppose that you have cron installed already; if not, then install some (vixie-cron for an example).

使用以下内容创建一个新文件 /etc/cron.d/.cron:

Create a new file /etc/cron.d/<any-name>.cron with the following content:

# run script every 5 minutes
*/5 * * * *   myuser  python /path/to/script.py

# run script after system (re)boot
@reboot       myuser  python /path/to/script.py

其中 myuser 是运行脚本的用户(出于安全原因,如果可能,它不应该是 root).如果这不起作用,请尝试将内容附加到 /etc/crontab.

where myuser is the user to run the script (it shouldn’t be root if possible, for security reasons). If this doesn’t work, then try to append the content to /etc/crontab instead.

您可能希望将脚本的 stdout/stderr 重定向到文件,以便检查是否一切正常.这与在 shell 中相同,只需添加类似 >>/var/log/<any-name>-info.log 2>>/var/log/<any-name>-error.log 在脚本路径之后.

You might want to redirect stdout/stderr of the script to file, so you can check if everything works fine. This is same as in shell, just add something like >>/var/log/<any-name>-info.log 2>>/var/log/<any-name>-error.log after the script path.

这篇关于编写每 5 分钟执行一次的 python 脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆