tags:

views:

146

answers:

2

If I'm using this with getopt:

import getopt
import sys

opts,args = getopt.getopt(sys.argv,"a:bc")
print opts
print args

opts will be empty. No tuples will be created. If however, I'll use sys.argv[1:], everything works as expected. I don't understand why that is. Anyone care to explain?

+3  A: 

It's by design. Recall that sys.argv[0] is the running program name, and getopt doesn't want it.

From the docs:

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

http://docs.python.org/library/getopt.html

Alan
+4  A: 

The first element of sys.argv (sys.argv[0]) is the name of the script currently being executed. Because this script name is (likely) not a valid argument (and probably doesn't begin with a - or -- anyway), getopt does not recognize it as an argument. Due to the nature of how getopt works, when it sees something that is not a command-line flag (something that does not begin with - or --), it stops processing command-line options (and puts the rest of the arguments into args), because it assumes the rest of the arguments are items that will be handled by the program (such as filenames or other "required" arguments).

mipadi
I understand now. Thanks!
Geo