Argparse: Check if any arguments have been passed

Framester picture Framester · May 22, 2012 · Viewed 57.3k times · Source

My script should start a demo mode, when the no parameters are given. I tried this:

args = parser.parse_args()
if len(args) == 0:
    run_demo()
else:
    # evaluate args

Which gives a *** TypeError: object of type 'Namespace' has no len() as args is no list.

How would I achieve what I want?

Answer

Dr. Jan-Philip Gehrcke picture Dr. Jan-Philip Gehrcke · May 22, 2012

If your goal is to detect when no argument has been given to the command, then doing this via argparse is the wrong approach (as Ben has nicely pointed out).

Think simple! :-) I believe that argparse does not depopulate sys.argv. So, if not len(sys.argv) > 1, then no argument has been provided by the user.