如何从python cgi脚本的子过程中捕获错误?

我正在尝试编写一个Python CGI脚本,该脚本将使用子过程调用sox(音频处理程序).问题是,当我从sox调用中获得错误时,所有程序崩溃,并且从Apache获得“格式错误的标头”错误.

相关位:

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 '<b>something went wrong in sox: returned error code ' +\
          retcode + ', but we are continuing anyway...</b>'
  """p = subprocess.Popen(sox)
  if p.stdout:
    print '<b>something happened in sox: returned ' +\
          p.stdout.read() + ', but we will keep going...</b>'
  if p.stderr:
    print '<b>something happened in sox: returned ' +\
          p.stderr.read() + ', but we will keep going...</b>'"""
...

def main():
  print "Content-Type: text/html\n\n"

...
    downsample(in_file, in_location, command, out_location)
...

if __name__ == '__main__':
  main()

我正在使用check_call允许cgi错误处理程序立即打印堆栈跟踪(以避免500页),但是我真的很想抓住错误,自己处理并继续执行脚本.我尝试通过将check_call封装在try中来做到这一点:CalledProcessError:语句除外,但这又导致了500页.被注释掉的那部分对我也不起作用.

从/ var / www / apache2 / error_log中获取:

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/

我不明白为什么在标题打印之前它似乎正在运行sox命令.或者,如果是,为什么会说标题错误?

解决方法:

听起来您正在使用缓冲输出.

如果真是这样,该命令的输出将打印在HTTP标头之前,因此Web浏览器会感到困惑.

您可以在执行系统调用之前调用sys.stdout.flush(),以确保输出缓冲区中的所有标头和html实际上都已打印.

希望这可以帮助.

上一篇:如何从python运行可执行文件并传递所需的参数?


下一篇:python-Gunicorn子流程引发异常[Errno 10]