简体   繁体   English

如何在LINUX上使用cron运行python脚本

[英]How to run a python script with cron on LINUX

I'm trying to run a python script on my raspberrypi using cron . 我正在尝试使用cron在raspberrypi上运行python脚本。

I did the following: 我做了以下工作:

crontab -e # To edit a crontab job

After the cron file opened, I added the following line: 打开cron文件后,我添加了以下行:

@reboot /usr/bin/python /home/pi/path/to/file/example.py > /home/pi/cronlogs/mylog.log # JOB_ID_!

If I understand the documentation correctly, this cron job should be executed every time after the system booted up. 如果我正确地理解了文档,则该cron作业应在系统启动后每次执行。 However in my case, when I reboot the computer, the script will not be executed. 但是,就我而言,当我重新启动计算机时,该脚本将不会执行。

What's strange: 奇怪的是:

  • I checked the log file and it's empty, so it seems like everything goes fine 我检查了日志文件,它是空的,所以看来一切正常
  • If I run the given command manually (so basically write the following code to the terminal) it executes and works correctly: /usr/bin/python /home/pi/path/to/file/example.py > /home/pi/cronlogs/mylog.log 如果我手动运行给定命令(因此基本上将以下代码写入终端),它将执行并正常运行: /usr/bin/python /home/pi/path/to/file/example.py > /home/pi/cronlogs/mylog.log

I guess I missed something really obvious but I can't see it. 我想我错过了确实很明显的东西,但我看不到。 Please can I ask for any advise how to debug this. 请问任何建议如何调试此。 Thanks! 谢谢!

The cron definition looks correct; cron定义看起来正确; I just checked this on my Pi running Debian stretch and it works OK: 我刚刚在运行Debian的Pi上检查了一下,效果很好:

@reboot /usr/bin/python /home/pi/example.py > /home/pi/mylog.log

Some other possible reasons it might not work: 其他可能的原因可能不起作用:

  • working directory issue (if you're using relative paths) 工作目录问题(如果您使用相对路径)
  • a long running script (being a scraping script it might take a while to complete) - you can check if it's still running using ps aux | grep python 长时间运行的脚本(作为抓取脚本可能需要一段时间才能完成)-您可以使用ps aux | grep python检查它是否仍在运行ps aux | grep python ps aux | grep python
  • the script does not output anything (would need some more details about the script) 该脚本不会输出任何内容(需要有关该脚本的更多详细信息)

Just to be sure you catch any errors from the script, redirect stderr to stdout by using 2>&1 为了确保您捕获了脚本中的任何错误,请使用2>&1stderr重定向到stdout

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM