How to use python argparse with args other than sys.argv?

前端 未结 2 2029
予麋鹿
予麋鹿 2020-12-17 09:34

I\'ve been all over the documentation and it seems like there\'s no way to do it, but:

Is there a way to use argparse with any list of strings, instead of only with

相关标签:
2条回答
  • 2020-12-17 09:56

    Just change the script to default to sys.argv[1:] and parse arguments omitting the first one (which is the name of the invoked command)

    import argparse,sys
    
    def main(argv=sys.argv[1:]):
        parser = argparse.ArgumentParser()
        # Do some argument parsing
        args = parser.parse_args(argv)
    
    if __name__ == '__main__':
        main()
    

    Or, if you cannot omit the first argument:

    import argparse,sys
    
    def main(args=None):
        # if None passed, uses sys.argv[1:], else use custom args
        parser = argparse.ArgumentParser()
        parser.add_argument("--level", type=int)
        args = parser.parse_args(args)
    
        # Do some argument parsing
    
    if __name__ == '__main__':
        main()
    

    Last one: if you cannot change the called program, you can still do something

    Let's suppose the program you cannot change is called argtest.py (I added a call to print arguments)

    Then just change the local argv value of the argtest.sys module:

    import argtest
    argtest.sys.argv=["dummy","foo","bar"]
    argtest.main()
    

    output:

    ['dummy', 'foo', 'bar']    
    
    0 讨论(0)
  • 2020-12-17 10:06

    You can pass a list of strings to parse_args:

    parser.parse_args(['--foo', 'FOO'])
    
    0 讨论(0)
提交回复
热议问题