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

2019-04-28 10:36发布

问题:

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.

回答1:

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.



回答2:

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