python如何从运行在子进程中的ghostscript命令捕获错误

2024-10-01 00:25:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我在一个子进程中运行ghostscript,它运行得很好,只是我似乎无法捕获错误。在

import subprocess

cmd = 'gs -dSAFER -dNOPAUSE -dBATCH -sDEVICE=jpeg -sOutputFile=img-%d.jpeg -r150 -g600x600 sample.pdf'
p = subprocess.Popen(cmd.split(), shell=False, stderr=subprocess.PIPE)

stderr = p.communicate()

print stderr

我的问题是命令是否正确执行stderr始终等于:

(无,')

我再次尝试指定stdout和stderr

^{pr2}$

p.stdout给出输出,但p.stderr仍然返回None


Tags: importcmdgs进程错误stderrstdoutjpeg
1条回答
网友
1楼 · 发布于 2024-10-01 00:25:40

Ghostscript似乎主要是写STDOUT的,除了致命错误的摘要,比如

GPL Ghostscript 8.71: Unrecoverable error, exit code 1

最后到了斯特德。所以,阅读STDOUT,你应该能够捕捉到所有的东西。在

为了帮助调试,请使用子进程打印在python中执行的命令,然后在shell中使用IO重定向将输出重定向到文件,以便查看流GS输出的内容。例如:gs [args] 2>stderr.txt 1>stdout.txt

另外,您应该使用shlex.split()而不是str.split()来标记参数列表,请参见note in the subprocess docs。在

在第二个网站上注意:一旦你开始替换示例.pdf'对于使用字符串格式(cmd % filename)的实际文件名,请确保使用%%d来转义%d(因为它是由GS而不是Python解释的)。在

相关问题 更多 >