Ibrahim Jafar Ibrahim Jafar - 1 month ago 9
Python Question

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
import 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?

Answer

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).

Comments