我正在尝试编写一个 Python CGI 脚本,它将使用子进程调用 sox(一个音频处理程序)。问题是,当我从 sox 调用中收到错误时,一切都崩溃了,我从 Apache 收到了“格式错误的 header ”错误。
相关位:
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 命令。或者,如果是,为什么说 header 格式不正确?
最佳答案
import subprocess
p = subprocess.Popen(cmd)
p.wait()
if p.returncode:
print "failed with code: %s" % str(p.returncode)
关于python - 如何在 python cgi 脚本中捕获来自子进程的错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5653377/