crontab: python script being run but does not execute OS Commands

感情迁移 提交于 2020-08-04 06:55:56

问题


I have this crontab configuration setup and the following script.

MAILTO="abc@avc.com"
41 15 * * * /usr/bin/python /home/atweb/Documents/opengrok/setup_and_restart.py >       /home/atweb/Documents/opengrok/restart_log.txt 2&>1

And the python script is as this

import subprocess
import os
from time import gmtime, strftime


def main():
    print(strftime("%a, %d %b %Y %X +0000", gmtime()))
    print('Running opengrok index..')
    subprocess.call(["cd", "/home/atweb/Documents/opengrok"])
    subprocess.call(["./stop_website"])
    print('Stopped website...')
    subprocess.call(["./index_opengrok"])
    print('finished indexing...')
    subprocess.call(["./setup_opengrok"])
    print('setup finished...')
    subprocess.call(["./start_website"])
    print('Finished opengrok index..')

if  __name__ =='__main__':main()

And this is the output log

Tue, 27 Aug 2013 22:41:01 +0000
Running opengrok index..

For some reason the script has begun running but other parts of the script are not finished. I am not sure if its OS fault or cron fault or python. The script by itself runs fine when I invoke it from command line.

Does anyone know why is this happening?


回答1:


You need shell to run cd command. In your crontab define sh or bash as SHELL.

SHELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
MAILTO="abc@avc.com" 
# m h dom mon dow   command
41 15 * * * /usr/bin/python /home/atweb/Documents/opengrok/setup_and_restart.py >       /home/atweb/Documents/opengrok/restart_log.txt 2&>1

Or open shell as subprocess in python.




回答2:


Two things: Your cd will set the directory for that subprocess, which immediately exits:

subprocess.call(["cd", "/home/atweb/Documents/opengrok"])

In other words, it's a wasted step.

The next subprocess doesn't know anything about the previous one's environment:

subprocess.call(["./stop_website"])

...so it won't be able to run. If you want all of your programs to run in that directory, use:

os.chdir("/home/atweb/Documents/opengrok")

before any of the subprocess.call() lines.



来源:https://stackoverflow.com/questions/18476757/crontab-python-script-being-run-but-does-not-execute-os-commands

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!