How can I use python's argparse with a predefined argument string?

前端 未结 4 1622
星月不相逢
星月不相逢 2020-12-09 09:23

I want to use the pythons argparse module to parse my cli parameter string. This works for the parameters a pass from terminal, but not with a given string.

         


        
相关标签:
4条回答
  • 2020-12-09 09:46

    parser.parse_args() expects a sequence in the same form as sys.argv[1:]. If you treat a string like a sys.argv sequence, you get ['s', 'o', 'm', 'e', 'T', 'e', 's', 't', 'F', 'i', 'l', 'e']. 's' becomes the relevant argument, and then the rest of the string is unparseable.

    Instead, you probably want to pass in parser.parse_args(['someTestFile'])

    0 讨论(0)
  • 2020-12-09 09:51

    Just like the default sys.argv is a list, your arguments have to be a list as well.

    args = parser.parse_args([argString])
    
    0 讨论(0)
  • 2020-12-09 09:52

    Simply split your command string :

    args = parser.parse_args(argString.split())
    

    A complete example to showcase :

    import argparse
    
    if __name__ == '__main__':
        parser = argparse.ArgumentParser()
        parser.add_argument('--dummy_opt', nargs='*', type=int, help='some ids')
        argString = "--dummy_opt 128 128"
        args = parser.parse_args(argString.split())
    
        print(args)
    

    will output :

    Namespace(pic_resize=[128, 128])

    0 讨论(0)
  • 2020-12-09 09:57

    Another option is to use shlex.split. It it especially very convenient if you have real CLI arguments string:

    import shlex
    argString = '-vvvv -c "yes" --foo bar --some_flag'
    args = parser.parse_args(shlex.split(argString))
    
    0 讨论(0)
提交回复
热议问题