Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python empty argument

how do I print help info if no arguments are passed to python script?

#!/usr/bin/env python

import sys

for arg in sys.argv:
    if arg == "do":
        do this
    if arg == ""
        print "usage is bla bla bla"

what I'm missing is if arg == "" line that I don't know how to express :(

like image 693
sfsd Avatar asked Feb 03 '10 17:02

sfsd


People also ask

How do you pass a blank argument in Python?

But in the general case, if you wanted to pass None to the function, what you can do is initialise a sentinel default_y = object() in the outer scope, and then check against that in the conditional.

Can an argument list be empty?

An empty argument list in a function definition indicates that a function that takes no arguments. An empty argument list in a function declaration indicates that a function may take any number or type of arguments.

Can you pass none as an argument?

None is often used as a default argument value in Python because it allows us to call the function without providing a value for an argument that isn't required on each function invocation.

How do you make an optional argument in Python?

You can define Python function optional arguments by specifying the name of an argument followed by a default value when you declare a function. You can also use the **kwargs method to accept a variable number of arguments in a function.


3 Answers

if len(sys.argv) == 1:
    # Print usage...

The first element of sys.argv is always either the name of the script itself, or an empty string. If sys.argv has only one element, then there must have been no arguments.

http://docs.python.org/library/sys.html#sys.argv

like image 102
Josh Wright Avatar answered Sep 22 '22 20:09

Josh Wright


if len(sys.argv)<2:

The name of the program is always in sys.argv[0]

like image 26
AJ. Avatar answered Sep 22 '22 20:09

AJ.


You can check if any args were passed in by doing:

#!/usr/bin/env python

import sys
args = sys.argv[1:]

if args:
    for arg in args:
        if arg == "do":
            # do this
else:
    print "usage is bla bla bla"

However, there are Python modules called argparse or OptParse (now deprecated) that were developed explicitly for parsing command line arguments when running a script. I would suggest looking into this, as it's a bit more "standards compliant" (As in, it's the expected and accepted method of command line parsing within the Python community).

like image 23
Mike Trpcic Avatar answered Sep 25 '22 20:09

Mike Trpcic