如何从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页),但是我真的很想抓住错误,自己处理并继续执行脚本。我尝试通过将try_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均已实际打印。 希望这可以帮助。     
import subprocess
p = subprocess.Popen(cmd)  
   p.wait()  
   if p.returncode:  
      print \"failed with code: %s\" % str(p.returncode) 
    
您可以使用subprocess.check_call并捕获“ 4”异常。
try:
    retcode = subprocess.check_call(sox)
except CalledProcessError:
    print \'<b>something went wrong in sox: returned error code \' +\\
      retcode + \', but we are continuing anyway...</b>\'
    

要回复问题请先登录注册