tags:

views:

292

answers:

6

Hello,

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 :(

+8  A: 
if len(sys.argv)<2:

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

AJ
I would have just said `== 1` but it's all the same.
Chris Lutz
+8  A: 
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

Josh Wright
+1  A: 
#!/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"
Noctis Skytower
the `if` followed by the `for` feels a bit redundant to me. I added a variation of your answer to show what I mean
gnibbler
+1  A: 

Based on Noctis Skytower's answer

import sys
args = sys.argv[1:]

for arg in args:
    if arg == "do":
        # do this

if not args:
    print "usage is bla bla bla"
gnibbler
There is a problem with your second example. You have to break before you enter the `else` block if you do not want it to run.
Noctis Skytower
@Noctis Skytower. Yeah you're right, I'll delete it
gnibbler
+4  A: 

As others have said, 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 is a Python module called OptParse that was 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).

Mike Trpcic
"Use optparse" is the right answer for non-trivial programs.
Troy J. Farrell
+1  A: 

I recommend you use the lib optparse [1], is more elegant :D

[1] More powerful command line option parser < http://docs.python.org/library/optparse.html >

Felipe Cardoso Martins
+1 for optparse!
jathanism