Referencing ini file fails in cron

2019-08-04 05:10发布

问题:

I have a python script that queries a database. I run it from the terminal with python3 myscript.py

I've added a cron task for it in my crontab file */30 9-17 * * 1-5 python3 /path/to/my/python/script\ directory\ space/myscript.py

The script imports a function in the same directory that parses login info for a database located in database.ini in the same directory. The database.ini is:

[postgresql]
host=my-db-host-1-link.11.thedatabase.com
database=dbname
user=username
password=password
port=10898

But currently cron outputs to the file in my mail folder:

Section postgresql not found in the database.ini file

The section is clearly present in the database.ini file, so what am I missing here?

回答1:

Instead of running "python3 myscript.py" in the directory where it is present, try running it from some other directory (like home directory). Most likely you will see the same issue.

Note that cron's current-working-directory is different on different systems. So, the safest method is to explicitly switch to the directory where your script is and run the command there:

cd /path/to/my/python/script\ directory\ space/ && python3 myscript.py


回答2:

Try this:

import os

...

change --> filename=database.ini

for --------> filename=os.path.dirname(__file__)+'/database.ini'