运行 使用 python 的控制台命令

Run console command with python

此代码直接在 CLI 中运行良好:

xmllint --xpath '//Entities[contains(ExpirationDate, '2015')]' app/sftp/file.xml > test.xml

现在,我需要在 Python 环境中执行相同的命令。这就是我正在尝试的:

def process_xml(path):
    call(["xmllint --xpath '//Entities[contains(ExpirationDate, '2015')]' app/sftp/file.xml > test.xml"])

这是错误,我运行来自同一位置的文件和命令:

OSError: [Errno 2] No such file or directory

如果您与衍生进程无关,您可以只使用 os.system()

但是,如果你真的想使用 subprocess.call 和流重定向,你必须像下面这样使用它:

with open('myfile', 'w') as outfile:
    subprocess.call(["xmllint", "--xpath", "//Entities[contains(ExpirationDate, '2015')]", "app/sftp/file.xml"], stdout=outfile)

请注意,subprocess.call 将程序名称及其参数作为字符串列表,可能是问题所在