简体   繁体   English

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

[英]python - how to capture errors from a ghostscript command run in a subprocess

I am running ghostscript in a subprocess, which is working well except I don't seem to be able to capture errors. 我在子进程中运行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

My problem is whether the command executes correctly or no the stderr always equals: 我的问题是命令是否正确执行或者stderr是否总是等于:

(None, '') (没有, '')

I made a second attempt specifying both stdout and stderr 我做了第二次尝试,指定了stdout和stderr

p = subprocess.Popen(slide_cmd.split(), shell=False, stdin=PIPE, stdout=PIPE, stderr=STDOUT)

p.stdout gives output but p.stderr still returns on None p.stdout给出输出但是p.stder仍然返回None

Ghostscript seems to write mostly to STDOUT, except for the summary of fatal errors like Ghostscript似乎主要写给STDOUT,除了像致命错误的总结

GPL Ghostscript 8.71: Unrecoverable error, exit code 1

which ends up on STDERR. 最终在STDERR上。 So, read STDOUT as well and you should be able to capture everything. 所以,阅读STDOUT也应该能够捕获所有内容。

In order to help debug this, print the command you're executing in python using subprocess and then use IO redirection in your shell to redirect output to files in order to see on that stream GS outputs what. 为了帮助调试这个,使用子进程打印你在python中执行的命令,然后在shell中使用IO重定向将输出重定向到文件,以便在该流上看到GS输出什么。 For example: gs [args] 2>stderr.txt 1>stdout.txt 例如: gs [args] 2>stderr.txt 1>stdout.txt

On a side note, you should use shlex.split() instead of str.split() to tokenize argument lists, see this note in the subprocess docs . 另外,您应该使用shlex.split()而不是str.split()来标记参数列表,请参阅子流程文档中的这个注释

On a second site note: Once you start substituting 'sample.pdf' with an actual filename using string formatting ( cmd % filename ), make sure you escape that %d (because it's meant to be interpreted by GS, not Python) by using %%d instead. 在第二个站点上注意:一旦你开始使用字符串格式化( cmd % filename )替换'sample.pdf'和实际文件cmd % filename ,请确保通过使用来逃避%d (因为它意味着由GS解释,而不是Python) %%d代替。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM