Zack
Zack

Reputation: 4375

Python programming - Windows focus and program process

I'm working on a python program that will automatically combine sets of files based on their names.

Being a newbie, I wasn't quite sure how to go about it, so I decided to just brute force it with the win32api.

So I'm attempting to do everything with virtual keys. So I run the script, it selects the top file (after arranging the by name), then sends a right click command,selects 'combine as adobe PDF', and then have it push enter. This launched the Acrobat combine window, where I send another 'enter' command. The here's where I hit the problem.

  1. The folder where I'm converting these things loses focus and I'm unsure how to get it back. Sending alt+tab commands seems somewhat unreliable. It sometimes switches to the wrong thing.

  2. A much bigger issue for me.. Different combination of files take different times to combine. though I haven't gotten this far in my code, my plan was to set some arbitrarily long time.sleep() command before it finally sent the last "enter" command to finish and confirm the file name completing the combination process. Is there a way to monitor another programs progress? Is there a way to have python not execute anymore code until something else has finished?

Upvotes: 0

Views: 1580

Answers (1)

Hugh Bothwell
Hugh Bothwell

Reputation: 56654

I would suggest using a command-line tool like pdftk http://www.pdflabs.com/tools/pdftk-the-pdf-toolkit/ - it does exactly what you want, it's cross-platform, it's free, and it's a small download.

You can easily call it from python with (for example) subprocess.Popen

Edit: sample code as below:

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'
)

Upvotes: 1

Related Questions