在 python 中调用带参数的 exe 和批处理有什么区别?
What is the difference between calling an exe with args in python and batch?
我正在尝试调用带有多个参数的 exe,它在命令提示符或批处理代码中有效,但在 python 中无效。
Batch/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.org
的 3.6.1
- PyCharm Community版本:2017.1.3
- 我叫的是商业软件,不是我自己的。
来自https://docs.python.org/3/library/subprocess.html:
shlex.split()
can be useful when determining the correct tokenization for args, especially in complex case.
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!
Note in particular that options (such as -input) and arguments (such as eggs.txt) that are separated by whitespace in the shell go in separate list elements, while arguments that need quoting or backslash escaping when used in the shell (such as filenames containing spaces or the echo command shown above) are single list elements.
应该是:
args = ['FooBar.exe', '-script', 'some file path']
我正在尝试调用带有多个参数的 exe,它在命令提示符或批处理代码中有效,但在 python 中无效。
Batch/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.org 的 3.6.1
- PyCharm Community版本:2017.1.3
- 我叫的是商业软件,不是我自己的。
来自https://docs.python.org/3/library/subprocess.html:
shlex.split()
can be useful when determining the correct tokenization for args, especially in complex case.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!
Note in particular that options (such as -input) and arguments (such as eggs.txt) that are separated by whitespace in the shell go in separate list elements, while arguments that need quoting or backslash escaping when used in the shell (such as filenames containing spaces or the echo command shown above) are single list elements.
应该是:
args = ['FooBar.exe', '-script', 'some file path']