Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can I catch errors from subprocess in a python cgi script?
    text
    copied!<p>I'm trying to write a Python CGI script that will call sox (an audio processing program) using subprocess. The problem is that when I get errors from the sox call, everything crashes and I get a "malformed header" error from Apache.</p> <p>The relevant bits:</p> <pre><code>def downsample(in_file, in_location, sox, out_location): """ run sox """ ... sox = shlex.split(sox) retcode = subprocess.check_call(sox) if not retcode == 0: print '&lt;b&gt;something went wrong in sox: returned error code ' +\ retcode + ', but we are continuing anyway...&lt;/b&gt;' """p = subprocess.Popen(sox) if p.stdout: print '&lt;b&gt;something happened in sox: returned ' +\ p.stdout.read() + ', but we will keep going...&lt;/b&gt;' if p.stderr: print '&lt;b&gt;something happened in sox: returned ' +\ p.stderr.read() + ', but we will keep going...&lt;/b&gt;'""" ... def main(): print "Content-Type: text/html\n\n" ... downsample(in_file, in_location, command, out_location) ... if __name__ == '__main__': main() </code></pre> <p>I'm using check_call to allow the cgi error handler to print the stack trace right now (to avoid the 500 page), but I'd really like to catch the error, handle it myself, and move on with the script. I tried doing that by wrapping the check_call in a try: except CalledProcessError: statement, but that just led to the 500 page again. That part that's commented out doesn't work for me, either.</p> <p>And from /var/www/apache2/error_log:</p> <pre><code>Wed Apr 13 10:08:21 2011] [error] [client ::1] sox FAIL formats: can't open input file `/tmp/wavs/haha/f.wav': WAVE: RIFF header not found, referer: http://localhost/~Valkyrie_savage/ [Wed Apr 13 10:08:21 2011] [error] [client ::1] malformed header from script. Bad header=\x1f\x8b\b: downsample.py, referer: http://localhost/~Valkyrie_savage/ </code></pre> <p>I can't understand why it seems to be running the sox command <i>before</i> the header prints. Or, if it is, why does it say the header is malformed?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload