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?
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).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With