arboc7
arboc7

Reputation: 5880

Python Subprocess returns non-zero exit status only in cron

I have a Python script that manages a series of CasperJS tasks and processes the result. It runs well from the command line, but when I run the script in cron, I get the error:

CalledProcessError: Command '['/path/to/casperjs', '/path/to/doSomething.js', 'args']' returned non-zero exit status 1

In Python, I call CasperJS:

response = subprocess.check_output(['/path/to/casperjs', '/path/to/doSomething.js', 'args'], shell=True)

I have tried shell=False and Popen as well, but I get the same result. I also tried making the entire command a string (instead of list), but that didn't help either.

Running '/path/to/casperjs /path/to/doSomething.js args' returns exit code 0 when run in the shell.

I have also added PATH=/usr/bin:/bin:/sbin:/usr/local/bin to my crontab to no avail. (As suggested in this question.)

Any ideas why I'm only getting this error in cron? Thanks!!

EDIT: In accordance with the answer below, setting shell=False and stderr=subprocess.STDOUT made everything work...

Upvotes: 7

Views: 28716

Answers (2)

harlan
harlan

Reputation: 1

This is because when shell=True is chosen, the first arg is interpreted differently than when shell=False. In the second case, string or array is allowed, but it appears when shell is used the string form is preferred.

The docs are vague about this: "If passing a single string, either shell must be True (see below) or else the string must simply name the program to be executed without specifying any arguments."

You can remedy this EITHER by setting shell=False or by setting it to true and passing in the command as a string.

Upvotes: 0

jdi
jdi

Reputation: 92637

You should try to capture stderr in addition to stdout so that you can find out exactly why the program is failing (assuming it does indeed print some errors for you)

cmd = ['/path/to/casperjs', '/path/to/doSomething.js', 'args']
response = subprocess.check_output(cmd, 
                shell=True,
                stderr=subprocess.STDOUT)

Upvotes: 11

Related Questions