如何在 Ubuntu / Apache 中 运行 带有 cronjob 的 python 脚本

How to run a python script with cronjob in Ubuntu / Apache

我正在尝试在我的 Apache2/Ubuntu 20.04 服务器中设置一个 cronjob。

我要执行的python文件如下:

def main():
print('TEST')
function()


def function():
    file1 = open("home/username/project/cron_test.txt","a")
    str1 = 'Test2 \n'
    file1.write(str1)
    file1.close() 

if __name__ == '__main__':
    main()

我将我的 cronjob 定义如下:

* * * * * /home/username/project/venv/bin/python3 /home/username/project/cron_test.py

当我在 putty 中 运行 命令时,它工作得很好,我得到了我想要的输出。 但是,当我将它放在 crontab 中时,python 脚本不会 运行.

知道我做错了什么吗?我尝试了各种不同的方法,例如 cd 进入项目文件夹然后 运行 它,以及在 python venv 和代码之间放置一个 -f ,但我没有得到任何更近了。

感谢帮助。

此致,

帕特里克

也许尝试将您的脚本转换为可执行的 python 脚本,

  1. 将您的 cronjob 更改为 * * * * * /home/username/project/cron_test.py
  2. 使您的脚本可执行,即在终端中 运行 chmod +x cron_test.py
  3. 将以下内容添加到脚本文件的顶部:#!/usr/bin/python3(或者 python 二进制文件所在的位置)

更改此行

file1 = open("home/username/project/cron_test.txt","a")

file1 = open("/home/username/project/cron_test.txt","a")