3

I have a shell script cron which calls a python script from same directory but when this cron is executing, i am not getting expected output from my python script and when i execute it manually my python script's output is as expected.

I have provided python script paths like /usr/bin/python room_wise.py

and given all shell params in shell script as well but still my python script is not called using the shell script cron.

Can anyone help me here?

4
  • 1
    Have you tried /usr/bin/python /path/to/room_wise.py ? Commented Oct 13, 2017 at 11:30
  • Yes @Nepho, i have tried both the things, Commented Oct 13, 2017 at 11:33
  • Is the output of which python /usr/bin/python as expected? Commented Oct 13, 2017 at 11:34
  • yes, it is /usr/bin/python Commented Oct 13, 2017 at 11:36

1 Answer 1

3

The big issue in cron jobs is the absolute directory locations and relative directory locations. You need to split the relative path out firstly as shown.

#!/usr/bin/env bash
dirName=`dirname $0`
baseName=`basename $0`
arg1=$1
arg2=$2
cd ${dirName} && python ./room_wise.py arg1 arg2

Then use crontab -e to add items to your user cron jobs and add the following:

PATH=/usr/bin:/bin:/sbin
30 00 * * * /my/directory/containing/room_wise_py.sh arg1 arg2 > /my/directory/containing/output.log 2>&1

You can see that I've added the PATH since this can sometimes be a problem with certain Operating system distributions. Also, the script exists in the same directory as the bash script, or you can pass the directory location as an argument if you modify the bash script to include dirname as $1.

Also you can see that I've directed all output to a log file. This is a really good idea since its sometimes very difficult to debug the process if something goes wrong.

Sign up to request clarification or add additional context in comments.

3 Comments

Remember to add #!/usr/bin/env python at the start of your python script if you haven't already done this. This is also an important aspect to get right when executing software from bash scripts in cron.
what does the line 2>&1 do at the end of the pipe?
@3pitt it is also redirecting the error output to the log file which was previous specified

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.