Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Failing to open a file using os.system()

Tags:

python

cmd

system

I'm coding a Python script which is using the application pdftk a few times to perform some operations.

For example, I can use pdftk in the windows command line shell to merge two pdf files like this:

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's how I tried doing it:

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

The above pdftk command works perfectly in the Windows shell. However, it fails to open the input files (1.pdf and 2.pdf) when I'm trying to execute it using Python's os.system(). Here's the error message I get from pdftk when trying to execute the command using Python's os.system():

Error: Failed to open PDF file: 1.pdf

Error: Failed to open PDF file: 2.pdf

Why does it happen? How can I fix it?

Please note: I know there are better ways to merge pdf files with Python. My question isn't about merging pdf files. That was just a toy example. What I'm trying to achieve is an ability to execute pdftk and other command line applications using Python.

like image 970
snakile Avatar asked Feb 02 '11 23:02

snakile


2 Answers

You can avoid (potential) problems with quoting, escaping, and so on, with subprocess:

import subprocess

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

It's just as easy to use as os.system, and even easier if you are building the argument list dynamically.

like image 50
Danilo Piazzalunga Avatar answered Nov 09 '22 11:11

Danilo Piazzalunga


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

>>> os.getcwd()
'/home/vz0'
>>> os.chdir('/some/path/to/pdf/files/')
like image 39
vz0 Avatar answered Nov 09 '22 09:11

vz0