Crontab not executing my python script every 5 minutes

Viewed 433

I know a lot of people ask the same but I can't see my fail.

My goal is execute a code every 5 minutes and this is my cron line,

*/5 * * * * /usr/bin/python3 /home/myUserName/folder-name-path/main.py

I did all what I know and find,

  • The first line of the script has #!/usr/bin/python3
  • If I execute my script without cron doesn't crash.
  • I did which python3 and says "/usr/bin/python3".

Can somebody explain me where I'm mistaking?

EDIT:

Following what @CherryDT has said, I must add that the structure of my project is similar to:

folder-name-path
   |-> lib (folder)  -> Some python scripts
   |-> data (folder) -> Some CSV data
   |-> temp (folder) -> A json file.

And inside my scripts I import the python files as from lib import foo.

EDIT2:

Ok the problem is not my cron script, the problem is the subfolders inside my main folder.

I tried scheduling another script without imports and works well. Then I'm practically sure the problem is with the imports. Can somebody say me what can I can I do? I tried starting with

import os
os.chdir(os.path.dirname(__file__))

But I have an error, FileNotFoundError: [Errno 2] No such file or directory: ''

I tried

cwd = os.getcwd()
print(cwd)

And I obtain the main path, /home/myUserName/folder-name-path.

Thank you very much!

1 Answers

Finally the problem was with the paths inside my code. Crontab needs the absolute paths.

As I see it doesn't has problems to arrive to the user, but if then you have different subfolders in your main folder it will crash.

What I did to solve it, is obtain the main path, cwd,

import os
cwd = os.getcwd()

And define all paths adding cwd at the beggining, for example in my case:

csv_data = cwd + '/folder-name-path/data/myData.csv'
json_data = cwd + '/folder-name-path/temp/myTemp.json'

Also I added __init__.py in my lib folder not sure if it was necessary but it helps to python to understand this folder has scripts.

Thanks!!

Related