我正在用 python 编写一个包装工具。该工具的调用如下:
<wrapper program> <actual program> <arguments>
包装程序只是添加一个参数并执行实际的程序:
<actual program> <arguments> <additional args added>
棘手的部分是有些字符串被转义,有些则没有转义
Example arguments format: -d \"abc\" -f "xyz" "pqr" and more args
包装器工具是通用的,除了添加额外的参数之外,它不应该知道实际的程序和参数
据我了解,这与shell有关。有关如何实现包装器工具的任何建议。
我尝试通过转义所有“”来实现。在某些情况下,“”在调用时没有转义,因此该工具无法正确执行实际程序。
是否可以保留用户提供的原始参数?
Wrapper.py 来源:
import sys
import os
if __name__ == '__main__':
cmd = sys.argv[1] + " "
args = sys.argv[2:]
args.insert(0, "test")
cmd_string = cmd + " ".join(args)
print("Executing:", cmd_string)
os.system(cmd_string)
输出:
wrapper.py tool -d "abc" -f \"pqr\" 123
Executing: tool test -d abc -f "pqr" 123
预期执行:tool test -d "abc"-f\"pqr\"123
最佳答案
在这里使用subprocess.call
,然后你就不用处理字符串/不必担心转义值等...
import sys
import subprocess
import random
subprocess.call([
sys.argv[1], # the program to call
*sys.argv[2:], # the original arguments to pass through
# do extra args...
'--some-argument', random.randint(1, 100),
'--text-argument', 'some string with "quoted stuff"',
'-o', 'string with no quoted stuff',
'arg_x',
'arg_y',
# etc...
])
如果您在获得调用的标准输出之后,如果您想检查结果,则可以执行 result = subprocess.check_output(...)
(或者也将被调用者的 stderr 通过管道传递给它)...请注意,从 3.5 开始,还有另一个高级助手 subprocess.run
涵盖了大多数用例。
值得检查 subprocess
中的所有辅助函数
关于python - 检索 Python 中的命令行参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51916775/