23

i've 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 to not use the flag -revs when use it, like this:

./somescript.py settings.json 1 2 3 4

1 Answer 1

38

Yes.

You have multiple solutions:

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

    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])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.