繁体   English   中英

如何使用argparse Python将'='用作参数分隔符?

[英]How to use '=' as an argument separator using argparse Python?

我想使用'='作为参数分隔符,并且在库文档中没有任何选择。 因此,argparse支持将'='用作参数分隔符/分隔符。

class Parse:
    def __init__(self):
        parser = argparse.ArgumentParser()
        parser.add_argument("script_config",help="Script Config File")
        parser.add_argument("devices",help="devices")
        parser.add_argument("log_file",help="log_file")
        parser.add_argument("result_file",help="result_file")
        parser.add_argument("testbed_file",help="testbed_file")
        parser.add_argument("runtime",help="Just Runetime")
        args = parser.parse_args()
        print pprint.pprint(args)

a=Parse()

输出到上面的代码,在这里我得到的运行时为runtime=10

 root@ip-:~/cloudzelera/$ python  ../lib/TestsuiteOption.py /tmp/abc.conf qa05__lnx1__i-12b651ea /tmp/123.suite /tmp/result.tmp /tmp/config runtime=10
Namespace(devices='qa05__lnx1__i-12b651ea', log_file='/tmp/123.suite', result_file='/tmp/result.tmp', runtime='runtime=10', script_config='/tmp/abc.conf', testbed_file='/tmp/config')
None

runtime不是可选参数,而是必需的位置参数。 因此,您永远不会在命令行上使用名称:

TestsuiteOption.py /tmp/abc.conf qa05__lnx1__i-12b651ea /tmp/123.suite /tmp/result.tmp /tmp/config 10

如果希望runtime是可选的,请用两个破折号(代表长名称)来启动该选项:

parser.add_argument("--runtime", help="Just Runtime")

并在命令行上使用相同的命令:

TestsuiteOption.py /tmp/abc.conf --runtime=10 qa05__lnx1__i-12b651ea /tmp/123.suite /tmp/result.tmp /tmp/config

现在,该选项可以在命令行的任何位置(包括开始位置)使用。

请注意, argparse使用UNIX命令行参数约定,其中可选参数以-表示短的1个字符的参数,以--表示长的参数。 它不适用于其他约定。

鉴于您指定的内容不符合Unix参数解析约定,为什么要在末尾添加另一行:

args.runtime = args.runtime.split('=')[1]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM