What’s the easiest, tersest, and most flexible method or library for parsing Python command line arguments?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
This answer suggests
optparsewhich is appropriate for older Python versions. For Python 2.7 and above,argparsereplacesoptparse. See this answer for more information.As other people pointed out, you are better off going with optparse over getopt. getopt is pretty much a one-to-one mapping of the standard getopt(3) C library functions, and not very easy to use.
optparse, while being a bit more verbose, is much better structured and simpler to extend later on.
Here’s a typical line to add an option to your parser:
It pretty much speaks for itself; at processing time, it will accept -q or –query as options, store the argument in an attribute called query and has a default value if you don’t specify it. It is also self-documenting in that you declare the help argument (which will be used when run with -h/–help) right there with the option.
Usually you parse your arguments with:
This will, by default, parse the standard arguments passed to the script (sys.argv[1:])
options.query will then be set to the value you passed to the script.
You create a parser simply by doing
These are all the basics you need. Here’s a complete Python script that shows this:
5 lines of python that show you the basics.
Save it in sample.py, and run it once with
and once with
Beyond that, you will find that optparse is very easy to extend. In one of my projects, I created a Command class which allows you to nest subcommands in a command tree easily. It uses optparse heavily to chain commands together. It’s not something I can easily explain in a few lines, but feel free to browse around in my repository for the main class, as well as a class that uses it and the option parser