当脚本作为cronjob运行时,python脚本在import语句处停止 [英] python script stops at import statement when script is run as cronjob

查看:82
本文介绍了当脚本作为cronjob运行时,python脚本在import语句处停止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我每30分钟用cron执行一次python脚本,但是它在import语句处停止,我不明白为什么,因为我没有得到任何反馈。

I'm executing a python script every 30 minutes with cron, but it stops at the import statement and I don't understand why because I don't get any feedback.

在我的crontab中,我有 * / 30 * * * * sh exec_script.sh

In my crontab I have */30 * * * * sh exec_script.sh

文件 exec_script.sh

cd /home/ziofil/python_scripts
python script_30_mins.py

在python脚本中,我有

In the python script I have

import logging
logging.basicConfig(filename="explicit_log.txt",level=logging.DEBUG)
logger = logging.getLogger(__name__)

logger.debug("script is executed")

# in the python_scripts folder there is a subfolder utilities/ that
# contains utility_1.py, were I define the class Utility
from utilities.utility_1 import Utility
logger.debug("Utility loaded")

utility = Utility()
logger.debug("object creation")

utility.do_your_thing()
logger.debug("done its thing")

如果我执行 python script_30_minutes.py ,一切正常,但使用cron时,执行将在 import 语句处停止(我读到脚本已执行,但要注意)。

If I execute python script_30_minutes.py from the terminal, everything works just fine, but with cron the execution stops at the import statement (I read "script is executed", but noting else).

出了什么问题?

更新:我将import语句放在中try / except 块,它记录了异常:没有名为Utility.utility_1的模块。我还尝试将Shell脚本中的PYTHONPATH变量设置为 / home / ziofil / python_scripts ,但仍然无法正常工作。

UPDATE: I put the import statement in a try/except block and it logged the exception: "No module named utilities.utility_1". I also tried to set the PYTHONPATH variable in the shell script to /home/ziofil/python_scripts, but it still doesn't work.

推荐答案

我发现了问题所在。 @UweMannl一直都是对的。 @mhawke指出cron的环境不同于我的终端环境后,我认为也许python二进制也可能有所不同,的确是:我想要 / home / ziofil / anaconda3 / bin / python 和cron正在使用 / usr / bin / python

I found out what the problem was. @UweMannl was right all along. After @mhawke pointed out that cron's environment is different than the one of my terminal, I thought that perhaps also the python binary could be different and indeed it was: I want /home/ziofil/anaconda3/bin/python and cron was using /usr/bin/python.

我修改了脚本的最后一行到 / home / ziofil / anaconda3 / bin / python script_30_mins.py ,一切正常!

I modified the last line of the script to /home/ziofil/anaconda3/bin/python script_30_mins.py and everything works!

这篇关于当脚本作为cronjob运行时,python脚本在import语句处停止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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