• Uncategorized

About python : crontab-runs-script-with-a-python-command-but-the-python-program-crashes

Question Detail

This is what crontab -l displays:


*/1 *   *   *   * /bin/bash  /home/azureuser/project/negev/restart.sh >> /home/azureuser/out.txt 2>&1

This is the content of the restart.sh file:


variable=$(ps x aux | grep -i 'main.py' | wc -l)
if test $variable=='1'
    /home/azureuser/miniconda3/envs/negev/bin/python '/home/azureuser/project/negev/main.py'

When I run main.py or restart.sh everything is super. However, when I go check the out.txt file I see this error:

Traceback (most recent call last):
    from logger import logger, logger_format
  File "/home/azureuser/project/negev/logger.py", line 8, in <module>
    log_path = config['LOGGER']['log_path']
  File "/home/azureuser/miniconda3/envs/negev/lib/python3.7/configparser.py", line 958, in __getitem__
    raise KeyError(key)
KeyError: 'LOGGER

The config file is in /home/azureuser/project/negev/user

I cannot understand why this is happening only when using crontab, and I have failed to find a solution anywhere.

EDIT: The problem is related to me using relative paths in the code and not the absolute paths. Is there a way to overcome this without changing every single relative path in my project?

Question Answer

Can you try adding os.chdir ‚Äčto your python code?

import os


# or
# os.chdir('/path/to/your/project/folder')
# os.chdir(os.path.dirname(__file__))

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.