python中的subprocess.call()没有生成文件,尽管没有生成错误



我使用的是下面的脚本,取自此处:https://github.com/theeko74/pdfc/blob/master/pdf_compressor.py

import os
import sys
import subprocess
def compress(input_file_path, output_file_path, power=0):
"""Function to compress PDF via Ghostscript command line interface"""
quality = {
0: '/default',
1: '/prepress',
2: '/printer',
3: '/ebook',
4: '/screen'
}
# Basic controls
# Check if valid path
if not os.path.isfile(input_file_path):
print("Error: invalid path for input PDF file")
sys.exit(1)
# Check if file is a PDF by extension
if input_file_path.split('.')[-1].lower() != 'pdf':
print("Error: input file is not a PDF")
sys.exit(1)
print("Compress PDF...")
initial_size = os.path.getsize(input_file_path)
subprocess.Popen(['gs', '-sDEVICE=pdfwrite', '-dCompatibilityLevel=1.4',
'-dPDFSETTINGS={}'.format(quality[power]),
'-dNOPAUSE', '-dQUIET', '-dBATCH',
'-sOutputFile={}'.format(output_file_path),
input_file_path])
compress("D:/Documents/Pdf Handler/test.pdf","D:/Documents/Pdf Handler/testCompress.pdf")

我想用它来压缩PDF,但当它运行时,会产生以下错误:

Traceback (most recent call last):
File "D:/Documents/Pdf Handler/compress.py", line 39, in <module>
compress("D:/Documents/Pdf Handler/test.pdf","D:/Documents/Pdf Handler/testCompress.pdf")
File "D:/Documents/Pdf Handler/compress.py", line 31, in compress
input_file_path]
File "C:Python37libsubprocess.py", line 323, in call
with Popen(*popenargs, **kwargs) as p:
File "C:Python37libsubprocess.py", line 775, in __init__
restore_signals, start_new_session)
File "C:Python37libsubprocess.py", line 1178, in _execute_child
startupinfo)
FileNotFoundError: [WinError 2] The system cannot find the file specified

经过一些研究,我发现我必须在subprocess.call:中添加shell=True

...
print("Compress PDF...")
initial_size = os.path.getsize(input_file_path)
subprocess.Popen(['gs', '-sDEVICE=pdfwrite', '-dCompatibilityLevel=1.4',
'-dPDFSETTINGS={}'.format(quality[power]),
'-dNOPAUSE', '-dQUIET', '-dBATCH',
'-sOutputFile={}'.format(output_file_path),
input_file_path])
compress("D:/Documents/Pdf Handler/test.pdf","D:/Documents/Pdf Handler/testCompress.pdf")

虽然这确实解决了出现错误的问题,但代码现在似乎并没有实际执行任何操作。它运行,但是没有任何文件添加到指定的目录中。

非常感谢您的帮助,正如我所提到的,我确实从其他地方获得了这段代码,而且文档非常稀少。

这不是一个真正的答案,但它旨在帮助您调试它。

您当前处于盲目飞行状态,因此需要检查stdout和stderr的输出,如下所示:

import subprocess
proc = subprocess.Popen(['gs', '-sDEVICE=pdfwrite', '-dCompatibilityLevel=1.4',
'-dPDFSETTINGS={}'.format(quality[power]),
'-dNOPAUSE', '-dQUIET', '-dBATCH',
'-sOutputFile={}'.format(output_file_path),
input_file_path],shell=True,stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
out, err = proc.communicate()
print(out)
print(err)

相关内容

最新更新