我用一个包含文件名的数组创建了一个脚本。该脚本通过目录和子目录递归搜索pdf文件,并将它们添加到数组中。然后它将一个字符串输出到pdftk的命令行中,以便合并它们。在
pdftk采用如下参数:
pdftk inputpdf1.pdf inputpdf2.pdf cat output output.pdf
但是,根据我从windows命令(上面列出的)得到的错误消息,输入的路径似乎不正确。我在Ubuntu上也遇到了同样的错误。在
^{pr2}$这是脚本的代码:
#----------------------------------------------------------------------------------------------
# Name: pdfMerger
# Purpose: Automatic merging of all PDF files in a directory and its sub-directories and
# rename them according to the folder itself. Requires the pyPDF Module
#
# Current: Processes all the PDF files in the current directory
# To-Do: Process the sub-directories.
#
# Version: 1.0
# Author: Brian Livori
#
# Created: 03/08/2011
# Copyright: (c) Brian Livori 2011
# Licence: Open-Source
#---------------------------------------------------------------------------------------------
#!/usr/bin/env python
import os
import glob
import sys
import fnmatch
import subprocess
path = str(os.getcwd())
x = 0
def process_file(_, path, filelist):
os.path.walk(os.path.realpath(topdir), process_file, ())
input_param = " ".join('"' + x + '"' for x in glob.glob(os.path.join(path, "*.pdf"))
output_param = '"' + os.path.join(path, os.path.basename(path) + ".pdf") + '"'
cmd = "pdftk " + input_param + " cat output " + output_param
os.system(cmd)
for filenames in os.walk (path):
if "Output" in filenames:
filenames.remove ("Output")
if os.path.exists(final_output) != True:
os.mkdir(final_output)
sp = subprocess.Popen(cmd)
sp.wait()
else:
sp = subprocess.Popen(cmd)
sp.wait()
def files_recursively(topdir):
os.path.walk(os.path.realpath(topdir), process_file, ())
files_recursively(path)
print "Finished Processing"
我到底做错了什么?在
File "C:\Documents and Settings\student3\Desktop\Test\pdftest2.py", line 32
output_param = '"' + os.path.join(path, os.path.basename(path) + ".pdf") + '"'
^
SyntaxError: invalid syntax
应该使用
os.system()
而不是subprocess.Popen
-如果将命令和参数作为列表给出,则此模块的内容可以正确处理文件名中的空格。在在你的例子中,那将是
然后呢
^{pr2}$因为有空格,所以需要用双引号括起来对路径进行转义。否则,shell将把每个空格解释为新文件的分隔符。在
还有几件事:
cat输出后缺少空格
... " cat output " + outputpath + ext)
您的
outputpath
变量为空。编辑:
你的代码有点混乱。我会将process_file方法更改为:
^{pr2}$我真不明白你为什么要在那里布置那些任务。在
编辑2:
以下是我的完整脚本:
这里是Pastebin
它产生的命令:
相关问题 更多 >
编程相关推荐