简体   繁体   English

如何在 Ubuntu / Apache 中使用 cronjob 运行 python 脚本

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

I am trying to set up a cronjob in my Apache2/Ubuntu 20.04 server.我正在尝试在我的 Apache2/Ubuntu 20.04 服务器中设置一个 cronjob。

The python file that I want to execute is as follows:我要执行的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()

I have defined my cronjob as follows:我已将我的 cronjob 定义如下:

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

When I run the command in putty, it works perfectly fine, and I get my desired output.当我在 putty 中运行命令时,它运行得非常好,我得到了我想要的输出。 However, when I place it in the crontab, the python script doesn't run.但是,当我将它放在 crontab 中时,python 脚本不会运行。

Any ideas what I am doing wrong?任何想法我做错了什么? I have tried various different ways, such as cd into the project folder and then run it, as well as putting a -f in between the python venv and the code, but I don't get any closer.我尝试了各种不同的方法,例如 cd 进入项目文件夹然后运行它,以及在 python venv 和代码之间放置一个 -f ,但我没有更接近。

Help is appreciated.帮助表示赞赏。

Best regards,此致,

Patrick帕特里克

Maybe Try converting your script to an executable python script,也许尝试将您的脚本转换为可执行的 python 脚本,

  1. Change your cronjob to * * * * * /home/username/project/cron_test.py将您的 cronjob 更改为* * * * * /home/username/project/cron_test.py
  2. Make your script executable, ie in terminal run chmod +x cron_test.py使您的脚本可执行,即在终端运行chmod +x cron_test.py
  3. Add the following to the top of your script file: #!/usr/bin/python3 (Or wherever your python binary is located)将以下内容添加到脚本文件的顶部: #!/usr/bin/python3 (或 Python 二进制文件所在的任何位置)

Change this line改变这一行

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

to

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM