python empty argument
how do I print help info if no arguments are passed to python script?
#!/usr/bin/env pytho开发者_开发技巧n
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 :(
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
if len(sys.argv)<2:
The name of the program is always in sys.argv[0]
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).
The following is a very Pythonic way of solving your problem, because it deliberately generates an exception within try .. except:
import sys
try:
sys.argv[1:] // do something with sys.argv[1:]
except IndexError:
print "usage is..."
sys.exit()
import argparse
def parse_args():
parser = argparse.ArgumentParser(
add_help=True,
)
# your arguments here
if len(sys.argv) == 1:
parser.print_help()
sys.exit(0)
else:
options = parser.parse_args()
return options
#!/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"
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"
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 >
精彩评论