python argh/argparse: How can I pass a list as a command-line argument?

后端 未结 2 755
悲哀的现实
悲哀的现实 2020-12-23 11:19

I\'m trying to pass a list of arguments to a python script using the argh library. Something that can take inputs like these:

./my_script.py my-func --argA          


        
相关标签:
2条回答
  • 2020-12-23 11:40

    With argparse, you just use type=int

    import argparse
    
    parser = argparse.ArgumentParser()
    parser.add_argument('-a', '--arg', nargs='+', type=int)
    print parser.parse_args()
    

    Example output:

    $ python test.py -a 1 2 3
    Namespace(arg=[1, 2, 3])
    

    Edit: I'm not familiar with argh, but it seems to be just a wrapper around argparse and this worked for me:

    import argh
    
    @argh.arg('-a', '--arg', nargs='+', type=int)
    def main(args):
        print args
    
    parser = argh.ArghParser()
    parser.add_commands([main])
    parser.dispatch()
    

    Example output:

    $ python test.py main -a 1 2 3
    Namespace(arg=[1, 2, 3], function=<function main at 0x.......>)
    
    0 讨论(0)
  • 2020-12-23 11:53

    I order to have access to each parameter value, the following code may be helpful.

    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument('-a', '--arg', nargs='+', type=int)
    args = vars(parser.parse_args())
    
    print "first parameter:" + str(args["arg"][0])
    print "second parameter:" + str(args["arg"][1])
    print "third parameter:" + str(args["arg"][2])
    
    0 讨论(0)
提交回复
热议问题