Search code examples
pythonpython-2.7argparse

How to make a python script work with and without arguments (default arguments)?


I am trying to get a Python script to work regardless when an argument has been passed or not.

The goal is to make the script functional as "MyPython.py" and "MyPython.py 5" should be able to work. If no argument has been passed, then the argument should be 0.

The variable imported_number should by default be 0 but if an argument has been detected, then it should take whatever number the user has passed.

import argparse

imported_number = 0

parser = argparse.ArgumentParser()
parser.add_argument("opt_number", type=int, help="Provide a number please")
args = parser.parse_args()

if args.opt_number > 0:
    imported_number=args.opt_number
    print "You provided me with the number " + imported_number
    print "You provided me with the number {}".format(args.opt_number)
else:
    print "You did not provide me with any number. Taking the default value, which is " + imported_number

Unfortunately I am getting the error: too few arguments error message.

Does anyone know of good and automated methods to get this task done? I'd appreciate it.


Solution

  • Use nargs, default, const like this:

    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument("opt_number", type=int, help="Provide a number please",
                        nargs='?', default=0, const=0)
    args = parser.parse_args()
    print(args)
    

    Your opt_number will be initialized with 0 when no argument is provided.