See here for related discussion on the merits of the various option and arg parsing choices we have in Python.
I'm making a diff script that does neat things with the output of Python's difflib
, and part of what that involves is handling the different ways that it can be called. For instance Git will send 7 args (the second and fifth being the files you want to diff) to the diff program you configure it with, and most differs are also expected to accept input as two file args. Interestingly, git's difftool
's --extcmd=
flag invokes the differ you specify with only the two args.
So, it's really easy to use OptionParser to do this since it just gives you a list of the args and I could grab the second and fifth ones and send them to fileinput
.
I did notice the big banner on the pydoc that says it's deprecated, so I was looking at argparse
.
It was not clear to me at all if it is even possible to configure argparse
to let your program accept a series of positional arguments without an option to "start it off". That is what I needed since I can't change the way e.g. Git would invoke the differ.
Anyway, I ended up doing some really trivial manipulation of sys.argv
, which after all is what I should have been doing to begin with in this particular situation.
if len(sys.argv) == 8:
# assume this was passed to git; we can of course do
# some parsing to check if we got valid git style args
args = [sys.argv[2], sys.argv[5]]
elif len(sys.argv) == 3:
args = sys.argv[:1]
else:
sys.exit("Not a valid number of args (2 or 7) to this diff program")
print "Files: " + ' '.join(args)
How might one use argparse to implement a program that simply attempts to open and read all of its arguments?
The reasoning is that for argparse
to deprecate parseopt
it must be possible to replicate all its functionality (within reason).