从评论到另一个答案,我知道您想要执行一些外部工具并将参数(文件名)传递给它。但是,此参数中有空格。
我建议接近;当然,我会使用subprocess
,而不是os.system
。
import subprocess
# Option 1
subprocess.call([path_to_executable, parameter])
# Option 2
subprocess.call("%s \"%s\"" % (path_to_executable, parameter), shell=True)
对我来说,两者都有效,请检查它们是否也适用于您。
说明:
选项 1 采用字符串列表,其中第一个字符串必须是可执行文件的路径,所有其他字符串都被解释为命令行参数。As subprocess.call knows about each of these entities, it properly calls the external so that it understand that
parameter` 将被解释为一个带空格的字符串 - 而不是两个或多个参数。
Option 2 is different. With the keyword-argument shell=True
we tell subprocess.call
to execute the call through a shell, i.e., the first positional argument is "interpreted as if it was typed like this in a shell". But now, we have to prepare this string accordingly. So what would you do if you had to type a filename with spaces as a parameter? You'd put it between double quotes. This is what I do here.