【问题标题】:How can I catch errors from subprocess in a python cgi script?如何从 python cgi 脚本中的子进程捕获错误?
【发布时间】:2011-08-04 22:23:51
【问题描述】:

我正在尝试编写一个 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: except 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 命令 before 标题打印。或者,如果是,为什么它说标头格式错误?

【问题讨论】:

    标签: python apache cgi subprocess


    【解决方案1】:
    import subprocess
    p = subprocess.Popen(cmd)  
       p.wait()  
       if p.returncode:  
          print "failed with code: %s" % str(p.returncode) 
    

    【讨论】:

      【解决方案2】:

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

      如果是这种情况,则命令的输出会在 HTTP 标头之前打印,因此Web 浏览器会感到困惑。

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

      希望这会有所帮助。

      【讨论】:

        【解决方案3】:

        您可以使用subprocess.check_call 并捕获CalledProcessError 异常。

        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>'
        

        【讨论】:

        • 我试过了.. 它实际上也导致了 500 页(又是格式错误的页眉错误)。
        猜你喜欢
        • 2021-02-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多