使用argparse保持参数不受影响

and*_*tti 6 python argparse

我想使用argparse来解析它知道的参数,然后保持其余的不变.例如,我希望能够运行

performance -o output other_script.py -a opt1 -b opt2
Run Code Online (Sandbox Code Playgroud)

哪个使用该-o选项,其余部分保持不变.

模块profiler.py与optparse做了类似的事情,但由于我正在使用argparse,我正在做:

def parse_arguments():
    parser = new_argument_parser('show the performance of the given run script')
    parser.add_argument('-o', '--output', default='profiled.prof')

    return parser.parse_known_args()

def main():
    progname = sys.argv[1]
    ns, other_args = parse_arguments()
    sys.argv[:] = other_args
Run Code Online (Sandbox Code Playgroud)

这似乎也有效,但如果other_script.py也有-o标志会发生什么?

通常有更好的方法来解决这个问题吗?

che*_*ner 16

您还可以向解析器添加位置参数nargs=argparse.REMAINDER,以捕获脚本及其选项:

# In script 'performance'...
p = argparse.ArgumentParser()
p.add_argument("-o")
p.add_argument("command", nargs=argparse.REMAINDER)
args = p.parse_args()
print args
Run Code Online (Sandbox Code Playgroud)

运行上面的最小脚本......

$ performance -o output other_script.py -a opt1 -b opt2
Namespace(command=['performance', '-a', 'opt1', '-b', 'opt2'], o='output')
Run Code Online (Sandbox Code Playgroud)


tit*_*ito 8

argparse将停止解析参数直到EOF或--.如果你想在没有被argparse解析的情况下获得参数,你可以写::

python [PYTHONOPTS] yourfile.py [YOURFILEOPT] -- [ANYTHINGELSE]
Run Code Online (Sandbox Code Playgroud)