0

I am trying to set up a cronjob in my Apache2/Ubuntu 20.04 server.

The python file that I want to execute is as follows:

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:

* * * * * /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. However, when I place it in the crontab, the python script doesn't run.

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.

Help is appreciated.

Best regards,

Patrick

2 Answers 2

1

Maybe Try converting your script to an executable python script,

  1. Change your cronjob to * * * * * /home/username/project/cron_test.py
  2. Make your script executable, i.e. in terminal run 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)
Sign up to request clarification or add additional context in comments.

Comments

0

Change this line

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

to

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

2 Comments

Hi Canasta, thanks for your edit, it did the job and it worked now. Now I wanted to change my code, and only run def function(). I changed the cron task to * * * * * /usr/bin/python3 -c 'from home.camielk.BolSellerTool.cron_test import function; function()' but now it isn't working anymore. Any more solutions?
It seems there is nothing wrong. Difference is /home/username/project/venv/bin/python3 changed to /usr/bin/python3. Check this, and Typo.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.