首页 > 解决方案 > Cron 作业(python 脚本)不写入 json 文件

问题描述

在 AWS EC2 上运行的 Ubuntu 机器 18.04。我有一个 python 脚本,它轮询 API 并将结果写入同一目录中的 json 文件。我已经设置了一个每 5 分钟运行一次的 cron 作业。问题是作业运行,我在日志中看到它,但没有写入文件。当我手动运行脚本时,json 文件按预期写入。

文件夹和 .py 文件权限为 775。

这是 crontab 条目(我从 访问它sudo crontab -e):

*/5 * * * * ubuntu python3 /home/ununtu/var/www/html/api.py > 
/home/ubuntu/var/www/html/cron.log 2>&1

cron.log 文件显示 Python 脚本的预期输出。 /var/log/syslog显示:

(root) CMD (ubuntu python3 /home/ununtu/var/www/html/api.py > 
/home/ubuntu/var/www/html/cron.log 2>&1) 

每五分钟。

请帮我解决这个问题。

标签: ubuntucronubuntu-18.04

解决方案


我有同样的问题,我无法解决它......

在我的情况下,我使用 python 库(BlockingScheduler)解决它并使用 tmux 在后台进程中执行它。

一个简单的使用示例:

from apscheduler.schedulers.blocking import BlockingScheduler

def test():
    test_write = 'hello'
    with open('logs.txt', 'a') as f:
        f.write('test: {}\n'.format(test_write))


scheduler = BlockingScheduler()
scheduler.add_job(test, 'interval', seconds=5)

scheduler.start()

希望能帮助到你!


推荐阅读