Several pits executed by python scripts in crontab

PS: Original article, if you need to reprint, please indicate the source, thank you!     

The address of this article: http://flyer0126.iteye.com/blog/2388142

 

    Small problems encountered in the work, feel free to record. Recently, I wrote a data synchronization python task script, which was executed manually, but it couldn't run in crontab. After a long time, I finally got it done.laughing out loud

 

    First, the absolute path problem

    Python commands in crontab use absolute paths, such as:

*/5 * * * * /usr/local/bin/python2.7 /home/work/user/main.py > /yyy.log 2>&1  

    The file path is involved in the program, and the relative path is changed to an absolute path, such as:

file = 'conf'
Change it to:
file = '/home/work/user/conf'

     Second, the environment variable problem

    The pre-installed python version may not be the actual version, which can be solved by using an absolute path (eg 1)

    If you need to take effect your bash information, you can add "source ~/.bashrc &&" in front, such as:

*/5 * * * * source ~/.bashrc && /usr/local/bin/python2.7 /home/work/user/main.py > /yyy.log 2>&1

    3. File executable permission 

    Set the executable permission of the python file,

chmod +x main.py

    Fourth, the crontab command cannot use functions

    Originally wanted to achieve log segmentation, use $(date -d "today" +"%Y%m%d_%H%M%S").log to achieve it, and found that it will not be executed after configuration, and can be changed to a fixed file solve. Note: It is also the problem that takes the longest time in this toss.

*/5 * * * * /usr/local/bin/python2.7 /home/work/user/main.py > /log/$(date -d "today" +"%Y%m%d_%H%M%S").log 2>&1
Change it to:
*/5 * * * * /usr/local/bin/python2.7 /home/work/user/main.py > /log/cron.log 2>&1

     

    If most crontab tasks are not executed, you can check them step by step through the above points. If there are any omissions, follow-up supplements~

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327032744&siteId=291194637