简体   繁体   English

Cron作业未与python导入模块一起运行

[英]Cron job not running with python import modules

I need to run a cron job on a python script to generate basemap plots. 我需要在python脚本上运行cron作业以生成底图图。

  1. The script by itself runs ok manually. 脚本本身可以手动运行。

  2. A simple print("Hello") at the start of the program with the rest commented out also runs ok on cron with 在程序开始时执行一个简单的print("Hello") ,其余部分都注释掉,在cron上也可以正常运行
    */10 * * * * /usr/bin/python3 ~/PythonFiles/TestScript.py > /dev/null 2>&1 >>log.txt

I made the file an executable using chmod +x and added a shebang ( #!/home/usr/anaconda3/bin/python ) at the start of the program. 我使用chmod +x使该文件成为可执行文件,并在程序开始时添加了shebang( #!/home/usr/anaconda3/bin/python )。 I can monitor activity in the log file via a printed message at the start of the program too 我也可以在程序开始时通过打印的消息来监视日志文件中的活动

  1. When I come to run the "normal" program which includes modules ( urllib.request, datetime, matplotlib, basemap, pygrib, numpy, ... ), the script then stops outputting anything to log.txt 当我运行包含模块( urllib.request, datetime, matplotlib, basemap, pygrib, numpy, ... )的“普通”程序时,脚本随后停止将任何内容输出到log.txt

So I suspect it is to do with modules and possibly their locations. 因此,我怀疑这与模块及其位置有关。 I checked and they seem to have been installed in various places (.../pkgs, .../conda-meta, .../site-packages , etc...) 我检查了一下,发现它们似乎已安装在各个地方(.../pkgs, .../conda-meta, .../site-packages等)。

First of all, is what I suspect correct? 首先,我怀疑是正确的吗?
Secondly, how do I fix it so that cron knows where to find all the libraries to run the job? 其次,如何解决此问题,以便cron知道在哪里可以找到运行该作业的所有库?

Many thanks! 非常感谢!

I suspected it was to do with module location paths. 我怀疑这与模块位置路径有关。 After trawling through websites and tweaking inputs to cron, the following works! 在浏览网站并调整对cron的输入后,以下工作有效!

SHELL=/bin/sh
HOME=/home/stephane
PYTHONPATH=/home/stephane/anaconda3/bin/python
PATH=/home/stephane/anaconda3/lib/python3.6/site-packages

*/2 * * * *  /home/stephane/anaconda3/bin/python ~/PythonFiles/TestScript.py >/dev/null 2>&1 >> log.txt

Note: matplotlib seems to need "import matplotlib as mpl; mpl.use('Agg')" to run off cron. 注意:matplotlib似乎需要“将matplotlib导入为mpl; mpl.use('Agg')”才能启动cron。

Thanks to all! 谢谢大家!

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

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