【问题标题】:Why cron job doesn't compile a python file?为什么 cron 作业不编译 python 文件?
【发布时间】:2020-08-14 22:50:27
【问题描述】:

Cron 无法编译我的 .py 文件,而且我无法从 Cron 收到电子邮件以了解 Cron 为何不起作用。但如果我只是在终端中运行命令~/t/test.sh,一切正常。

cron 中的代码:

SHELL=/bin/bash
MAILTO=mymail@gmail.com
30 0-23 1-31 1-12 0-6 ~/t/test.sh

我想运行一个脚本test.sh,它的代码是:

#!/bin/bash
cd /home/alex/t && python3.8 ./test.py

test.py中的代码:

from datetime import datetime
current_time = datetime.now()
f = open("text.txt", 'w+')
f.write("Hello world! Now is {0}\n".format(current_time))
f.close()

我通过 sudo crontab-ecrontab-e 命令启动了 Cron。我将 Cron 放在第一行 MAILTO=mymail@gmail.com。 我安装了yum install mailx。我尝试将命令>/dev/null 2>&1 添加到 Cron,即写 * * * * * ~/t/test.sh >/dev/null 2>&1 没有什么帮助 我使用 Ubuntu 18.04 Python3.8.2 以下是grep CRON /var/log/syslog 命令显示的日志:

Apr 30 15:35:01 av CRON[2130]: (alex) CMD (~/t/test.sh)

Apr 30 15:35:01 av CRON[2129]: (alex) MAIL (mailer 68 bytes of output put get status 0x004b from MTA#012)

有人遇到过这个问题吗? 你能帮忙吗?

【问题讨论】:

    标签: python linux ubuntu cron


    【解决方案1】:

    你的 test.sh 应该是这样的:(需要完整路径)

    #!/bin/bash
    /"location where python is installed"/python/bin/python /home/alex/t/test.py
    

    【讨论】:

      【解决方案2】:

      代码中最薄弱的环节是调用 Python 3.8 解释器时没有完整路径。您使用完整的绝对路径调用 bash,cd 到绝对路径,并通过您 cd-ed 进入的目录的路径访问您的脚本。只有 Python 假设 PATH 环境变量中存在一些目录。

      尝试通过其位置的完整路径访问 Python 3.8。

      【讨论】:

        最近更新 更多