command-line options and arguments using getopt
I'm trying to write a piece of code in python to get command-line options and arguments using getopt module. Here is my code:
import getopt
impor开发者_如何学编程t sys
def usage ():
print('Usage')
def main():
try:
opts, args = getopt.getopt(sys.argv[1:], 'xy:')
except getopt.GetoptError as err:
print(err)
usage()
sys.exit()
for o,a in opts:
if o in ("-x", "--xxx"):
print(a)
elif o in ("-y", "--yyy"):
print(a)
else:
usage()
sys.exit()
if __name__ == "__main__":
main()
The problem is that I can't read the argument of option x
, but I can read the argument of y
. What should I do to fix this?
Try getopt.getopt(sys.argv[1:], 'x:y:')
http://docs.python.org/library/getopt.html
Parses command line options and parameter list. args is the argument list to be parsed, without the leading reference to the running program. Typically, this means sys.argv[1:]. options is the string of option letters that the script wants to recognize, with options that require an argument followed by a colon (':'; i.e., the same format that Unix getopt() uses).
If you want to read argument then the option should've ':' next to it, there are few options which doesn't need argument like 'help' and 'verbose' which don't need ':' to be followed.
import getopt
import sys
def usage ():
print('Usage')
def main():
try:
opts, args = getopt.getopt(sys.argv[1:], 'x:y:h', ['xxx=', 'yyy=', 'help='])
except getopt.GetoptError as err:
print(err)
usage()
sys.exit()
for opt,arg in opts:
if opt in('-h', '--help'):
usage()
sys.exit( 2 )
elif opt in ('-x', '--xxx'):
print(arg)
elif opt in ('-y', '--yyy'):
print(arg)
else:
usage()
sys.exit()
if __name__ == "__main__":
main()
精彩评论