Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a bash parameter to a python script in a cron job?

I have a python application that uses getopt() to parse the command line for parameters. It works fine in an interactive bash shell, or in a bash script that is called from the command line, bit it will not execute when being called from within a bash shell script via cron. I am using Fedora 15.

The application fails when called as a cron job, issuing the following error in /var/log/messages:

myscript.py: abrt: detected unhandled Python exception in myscript.py

It seems that the command line parameters aren't being passed to the python script properly.

For example, the following command line invocation works properly, setting the input filename to "input.txt" and setting the "log" and "timer" flags to their desired values:

python myscript.py -i input.txt --log --timer

When I attempt to invoke the program via a bash script at the command line, the bash script works fine. But when I attempt to run the bash script via cron, execution fails with the aforementioned error.

I am at a loss to determine why the shell script fails to execute properly via cron. I am using full path names from within the bash script used for the cron job, so environment paths shouldn't be an issue:

/usr/bin/python /path/to/myscript.py -i /path/to/input.txt --log --timer

I am thinking that this syntax, when used in a bash script called via cron, might be passing the script's parameters to python, rather than to myscript.py.

Any help would be appreciated!

like image 601
bob Avatar asked Oct 11 '22 20:10

bob


1 Answers

While I agree with both comments, one way to debug issues with crontab entries is to be sure you're getting all the error messages. Are you looking at the cron users email file? Any un-captured output from cron is sent as an email to the userID. (If the user doesn't have an email account on the cron'ed machine, that is a seperate problem).

In any case, I find it helpful to explicitly capture the output. If I don't get output files, (at least zero sized files), then I know the crontab didn't even run.

Here's a sample crontab entry set up to capture all the output.

59 13 05 06 * { /usr/bin/python /path/to/myscript.py -i /path/to/input.txt --log --timer ; } > /tmp/myProj/myscriptPY.trace.`/bin/date +\%Y\%m\%d.\%H\%M` 2>&1

Recall (per @cji 's reminder), that cron will use /bin/sh (which on systems may wind up being bash anyway, so any variable assingments you include on the command line are better done like 69 13 05 06 * { var=1 ; export var ; cmds ... ; } ...

I've never had occasion to 'source' an environment variables file from a crontab, but I would expect it to work with . /path/to/envFile.

IHTH

like image 155
shellter Avatar answered Oct 17 '22 20:10

shellter