Python argparse: arg without flag

I have the following code:

parser.add_argument('file', help='file to test') parser.add_argument('-revs', help='range of versions', nargs='+', default=False) 

Is there a way not to use the -revs flag when using it, for example:

 ./somescript.py settings.json 1 2 3 4 
+6
source share
1 answer

Yes.

You have several solutions:

  • As Mrav mentioned, you can use the system argument (sys.argv [0 ...])
  • Or use argparse. From the documentation (which complies with python3 requirements), you can do this:

     if __name__ == '__main__': parser = ArgumentParser() parser.add_argument('file') parser.add_argument('revs', metavar='N', type=int, nargs='+', help='revisions') res = parser.parse_args() pprint(res) 

And you can see the result:

 $ ./test.py settings.json 1 2 3 Namespace(file='settings.json', revs=[1, 2, 3]) 
+10
source

Source: https://habr.com/ru/post/969595/


All Articles