Python: inability to open a file with os.system ()

I am coding a Python script that uses the pdftk application several times to perform some operations.

For example, I can use pdftk on the Windows command line to merge two PDF files, for example:

pdftk 1.pdf 2.pdf cat output result.pdf 

I would like to perform the above operation in the middle of my Python script. Here is how I tried to do this:

 os.system('pdftk 1.pdf 2.pdf cat output result.pdf') 

The above pdftk command works fine in the windows shell. However, it cannot open the input files (1.pdf and 2.pdf) when I try to execute it using Python os.system() . Here's the error message I get from pdftk when I try to execute a command using Python os.system() :

Error: Failed to open the PDF file: 1.pdf

Error: Could not open the PDF file: 2.pdf

Why is this happening? How can i fix this?

Please note: I know that there are ways to merge PDF files with Python. My question is not about merging PDF files. It was just a toy example. What I'm trying to achieve is the ability to run pdftk and other command line applications using Python.

+6
python cmd system
source share
2 answers

You can avoid (potential) problems when quoting, escaping, etc. using subprocess :

 import subprocess subprocess.call(['pdftk', '1.pdf', '2.pdf', 'cat', 'output', 'result.pdf']) 

It is as easy to use as os.system , and even easier if you are building a list of arguments dynamically.

+3
source share

You need to set the current working directory of the process. If the .pdf files are located in /some/path/to/pdf/files/ :

 >>> os.getcwd() '/home/vz0' >>> os.chdir('/some/path/to/pdf/files/') 
+2
source share

All Articles