【问题标题】:What is the difference between calling an exe with args in python and batch?在 python 和批处理中调用带有 args 的 exe 有什么区别?
【发布时间】:2017-06-12 16:12:45
【问题描述】:

我正在尝试使用多个参数调用一个 exe,它可以在命令提示符或批处理代码中工作,但在 python 中却不行。

批处理/cmd代码

"FooBar.exe" -script "some file path"

尝试了 Python 代码

from subprocess import call
args = ['FooBar.exe','-script','"some file path"']
call(args)

args = ['FooBar.exe -script "some file path"']
call(args)

args = ['FooBar.exe', '-script "some file path"']
call(args)

当我使用 python 代码时,批处理代码工作正常,但参数没有正确传递给软件(它不使用参数)。

这两种方法之间的参数传递方式是否存在根本区别?

如果我使用的是相关的:

【问题讨论】:

    标签: python python-3.x cmd arguments exe


    【解决方案1】:

    来自https://docs.python.org/3/library/subprocess.html:

    shlex.split() 在确定 args 的正确标记时很有用,尤其是在复杂情况下。

    import shlex, subprocess
    command_line = input()
    /bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
    args = shlex.split(command_line)
    print(args)
    ['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
    p = subprocess.Popen(args) # Success!
    

    请特别注意,shell 中由空格分隔的选项(例如 -input)和参数(例如 egg.txt)放在单独的列表元素中,而在 shell 中使用时需要引用或反斜杠转义的参数(例如包含空格的文件名或上面显示的 echo 命令)是单个列表元素。

    应该是:

    args = ['FooBar.exe', '-script', 'some file path']
    

    【讨论】:

    • 啊!当时不需要在路径周围引用,尝试了所有组合,但现在正在工作,欢呼。
    猜你喜欢
    • 2016-03-27
    • 1970-01-01
    • 1970-01-01
    • 2016-06-11
    • 2015-11-28
    • 1970-01-01
    • 1970-01-01
    • 2014-04-15
    • 2012-06-17
    相关资源
    最近更新 更多