2

I want to run a crontab which will run my file every hour at 0 minutes. I have the (sudo) crontab set up with a single command as follows:

0 * * * * /usr/bin/python3 /usr/folder/test.py

The crontab is running and as far as I can tell is correct, but my python file is not returning the absolute path when the file is run from another location.

What I need is a way to guarantee the absolute path of this text file when it is accessed from the root so that my crontab can run the file.

I've tried using both Path(filename).resolve(), and os.path.abspath(filename) but neither of them work.

import os
print(os.path.abspath("checklist.txt"))
python3 usr/folder/test.py

When I run the file "test.py" while within the folder, I get the expected output

python3 test.py

/usr/folder/checklist.txt

however when I run the same file from the root and access it via a path I get a different result, making using crontab impossible in this context

python3 usr/folder/test.py

/checklist.txt

Community
  • 1
  • 1
Conch
  • 56
  • 5
  • [What is the 'working directory' when cron executes a job?](https://unix.stackexchange.com/q/38951), [How to get full path of current file's directory in Python?](https://stackoverflow.com/q/3430372/608639), [Why would one use both, os.path.abspath and os.path.realpath?](https://stackoverflow.com/q/37863476/608639), [python os.path.realpath not working properly](https://stackoverflow.com/q/9887259/608639), etc. – jww Jun 17 '19 at 18:29

2 Answers2

6

If checklist.txt is in the same folder as your test.py script, then you can use the __file__ variable to get the right path. For example

# The directory that 'test.py' is stored
directory = os.path.dirname(os.path.abspath(__file__))
# The path to the 'checklist.txt'
checklist_path = os.path.join(directory, 'checklist.txt')
Jack
  • 2,625
  • 5
  • 33
  • 56
2

__file__ attribute

import os
filename = 'checklist.txt'
abs_path_to_file = os.path.join(os.path.dirname(__file__), filename)

sys module

import os, sys
filename = 'checklist.txt'
abs_path_to_file = os.path.join(os.path.dirname(sys.argv[0]), filename)
crissal
  • 2,547
  • 7
  • 25