Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't getopt working if sys.argv is passed fully?

Tags:

python

getopt

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?

like image 543
Geo Avatar asked Oct 08 '09 20:10

Geo


2 Answers

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

like image 61
mipadi Avatar answered Sep 28 '22 05:09

mipadi


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

like image 30
Alan Avatar answered Sep 28 '22 05:09

Alan