【发布时间】:2023-02-15 05:12:57
【问题描述】:
我试图在基于 linux 的操作系统中定期运行一些 python 脚本,经过快速研究后,我发现 crontab 是一种经典的方法。我是该命令的新手,所以我确保牢记常见的现有recommendations,并且(谨慎地)我决定首先使用一个非常简单的 python 代码,myscript.py:
#!/usr/bin/python3
print("If you see this, your periodic code ran OK!")
这'cron 表'(crontab -l) 文件如下所示,它应该每分钟运行一次myscript.py(我想快速测试一下):
* * * * * /usr/bin/python3 /home/my_user_folder/Desktop/test/myscript.py
几秒钟过去了,脚本到达了第一分钟……什么也没发生。到 ”解决这个问题”,我尝试了几件事,但(对我来说)诡异地我意识到大多数(如果不是全部)教程和帖子,用于将消息存储在。TXT或类似文件。我通过将 myscript.py 修改为:
#!/usr/bin/python3
# NOTES:
# 1. This code is the 'final version' after several trials
# 2. Remember that I was aiming to automate anything, just
# to get familiar with `crontab`; in this case, storing
# the current time to some .txt file was enough.
import time
t = time.localtime()
current_time = time.strftime("%H:%M:%S", t)
with open('/home/my_user_folder/Desktop/test/readme.txt', 'a') as f:
f.write(current_time)
f.write('\n')
...和有效.我觉得有点傻,因为我开始意识到我最初的实现(关于代码、环境设置、权限等)确实从一开始就是正确的,但是使用 Python 命令 print 来“测试”带有 crontab 的循环任务“无效”...
为什么?
【问题讨论】:
标签: python-3.x linux cron