Python编程 - Windows焦点和程序进程
我正在做一个Python程序,目的是根据文件名自动合并一组文件。
作为一个新手,我不太确定该怎么做,所以我决定直接用win32api来强行实现。
我尝试用虚拟按键来完成所有操作。首先,我运行脚本,它会选择第一个文件(在按名字排序后),然后发送一个右键点击的命令,选择“合并为Adobe PDF”,接着再按一下回车。这会打开Acrobat的合并窗口,然后我再发送一个“回车”命令。问题就出现在这里。
我在转换文件的文件夹失去了焦点,我不知道怎么把它找回来。发送alt+tab的命令似乎不太可靠,有时候会切换到错误的窗口。
对我来说,更大的问题是,不同组合的文件合并所需的时间不同。虽然我还没写到这部分代码,但我的计划是设置一个很长的time.sleep()命令,在最后发送“回车”命令之前,等待一段时间以确认文件名完成合并过程。有没有办法监控其他程序的进度?有没有办法让Python在其他事情完成之前不执行更多代码?
1 个回答
1
我建议你使用一个命令行工具,比如 pdftk,http://www.pdflabs.com/tools/pdftk-the-pdf-toolkit/。这个工具正好能满足你的需求,它可以在不同的操作系统上使用,而且是免费的,下载也很小。
你可以很方便地通过 Python 来调用它,比如使用 subprocess.Popen 这个方法。
编辑:下面是一个示例代码:
import subprocess
import os
def combine_pdfs(infiles, outfile, basedir=''):
"""
Accept a list of pdf filenames,
merge the files,
save the result as outfile
@param infiles: list of string, names of PDF files to combine
@param outfile: string, name of merged PDF file to create
@param basedir: string, base directory for PDFs (if filenames are not absolute)
"""
# From the pdftk documentation:
# Merge Two or More PDFs into a New Document:
# pdftk 1.pdf 2.pdf 3.pdf cat output 123.pdf
if basedir:
infiles = [os.path.join(basedir,i) for i in infiles]
outfile = [os.path.join(basedir,outfile)]
pdftk = [r'C:\Program Files (x86)\Pdftk\pdftk.exe'] # or wherever you installed it
op = ['cat']
outcmd = ['output']
args = pdftk + infiles + op + outcmd + outfile
res = subprocess.call(args)
combine_pdfs(
['p1.pdf', 'p2.pdf'],
'p_total.pdf',
'C:\\Users\\Me\\Downloads'
)