检索 Python 中的命令行参数

Retrieving the cmd line arguments as it is in Python

我正在 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 然后你就不用处理 strings/having 来担心转义值等......

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

中的所有辅助函数