Crontab not executing a Python script?

前端 未结 15 1452
囚心锁ツ
囚心锁ツ 2020-11-29 20:42

My python script is not running under my crontab.

I have placed this in the python script at the top:

#!/usr/bin/python

I hav

相关标签:
15条回答
  • 2020-11-29 20:49

    This might be helpful for someone. I was having this same issue (or at least a similar issue) and what helped me was to get the path in which Python (Be aware of the version you want to use python, python3, etc...) by running this:

    which python3
    

    And then, I replaced python3 for the full path of python3 in my crontab file.

    0 讨论(0)
  • 2020-11-29 20:50

    It is possible that the script does not start because it cannot locate the python interpreter. Crontab environment may be very different from the shell environment which you are using. The search paths may be differ significantly. Also, you test your script by starting the python interpreter explicitly while you expect the crontab to only start the script. I put this line at the top of my python scripts:

    \#!/bin/env python

    This line will help locate the interpreter regardless of which directory it is installed in as long as it is in the search path.

    0 讨论(0)
  • 2020-11-29 20:50
    • Is the cron user (where the script fails) and the terminal user (when the script succeeds) are same ?
    • Can you redirect the job output to some file as mentioned in Cron Job Log - How to Log?. We could see whether that helps.
    0 讨论(0)
  • 2020-11-29 20:51

    While the answers here clearly delineate the problem and solution, I wanted to add another answer which helped me.

    If your python script is calling a database, then be sure you can connect to the db properly within the cron env (to identify the cron env--> https://askubuntu.com/questions/23009/reasons-why-crontab-does-not-work). I had a file that would run from the shell, but not as a crontab unless I connected to the database as root from within the python script.

    0 讨论(0)
  • 2020-11-29 20:52

    Sometimes I am facing same problem. Whatever I try something as advised here, I may not get result.

    So I begin to write "trigger" bash script as follow (let's name it trigger.sh):

    #!/bin/bash
    
    /full_path/python_script.py
    

    And I am calling trigger.sh from crontab and everything is fine.

    EDIT: Of course, don't forget to do following (give execution right):

    $chmod +x python_script.py
    $chmod +x trigger.sh
    
    0 讨论(0)
  • 2020-11-29 20:53

    Easiest way to handle this is to add your python installation's path to PATH in top of the shell script. Something like:

    #!/usr/bin/env bash
    export PATH="{path to your python installation}:$PATH"
    python {python_file_name}.py
    

    As @Shargors said you can test it by

    env -i /bin/bash --noprofile --norc
    
    0 讨论(0)
提交回复
热议问题