简体   繁体   English

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

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

I want to use '=' as argument separator and didn't get any option in library documentation. 我想使用'='作为参数分隔符,并且在库文档中没有任何选择。 So, '=' supported as a argument separator/deliminator by argparse. 因此,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()

Output to above code, Here I got runtime as runtime=10 . 输出到上面的代码,在这里我得到的运行时为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 is not an optional argument, it is a required, positional argument. runtime不是可选参数,而是必需的位置参数。 As such you'd never use the name on the command line: 因此,您永远不会在命令行上使用名称:

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

If you want runtime to be optional, start the option with two dashes (for a long name): 如果希望runtime是可选的,请用两个破折号(代表长名称)来启动该选项:

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

and use the same on the command line: 并在命令行上使用相同的命令:

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

Now the option can be used anywhere on the command line, including at the start. 现在,该选项可以在命令行的任何位置(包括开始位置)使用。

Note that argparse uses the UNIX convention of command line arguments, where optional arguments start with - for short 1-character arguments, -- for long arguments. 请注意, argparse使用UNIX命令行参数约定,其中可选参数以-表示短的1个字符的参数,以--表示长的参数。 It is not suitable for other conventions. 它不适用于其他约定。

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

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

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

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