Python:无法使用os.system()打开文件 [英] Python: Failing to open a file using os.system()

查看:1393
本文介绍了Python:无法使用os.system()打开文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个Python脚本,该脚本正在使用应用程序 pdftk 几次执行一些操作。

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

例如,我可以在Windows命令行外壳中使用pdftk合并两个pdf文件,如下所示:

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

我想在我的Python脚本中间执行上述操作。这是我尝试的操作方式:

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

上面的pdftk命令在Windows shell中可以很好地工作。但是,当我尝试使用Python的 os.system()执行输入文件时,它无法打开输入文件(1.pdf和2.pdf)。这是我尝试使用Python的 os.system()执行命令时从pdftk中收到的错误消息:

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():


错误:无法打开PDF文件:
1.pdf

Error: Failed to open PDF file: 1.pdf

错误:无法打开PDF文件:
2 .pdf

Error: Failed to open PDF file: 2.pdf

为什么会发生?我该如何解决?

Why does it happen? How can I fix it?

请注意:我知道有更好的方法可以将pdf文件与Python合并。我的问题不是关于合并pdf文件。那只是一个玩具的例子。我想要实现的功能是能够使用Python执行pdftk和其他命令行应用程序。

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.

推荐答案

您可以通过 subprocess <来避免引用,转义等潜在的问题。 / code>:

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

它与 os.system 一样容易使用,并且如果您动态地构建参数列表,则更加容易。

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

这篇关于Python:无法使用os.system()打开文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆