Main Content
Command line parameter handling in Python via the argparse module Archive - Originally posted on "The Horse's Mouth" - 2015-12-08 18:55:44 - Graham Ellis
A new example from the Python course just completed - looking at command line parameters through the argparse module from the standard Python library (2.7 and 3.2 onwards), and XML handling through the xml.etree.ElementTree module (2.5 onwards)
Here's code setting up an argument parser:
parser = argparse.ArgumentParser()
parser.add_argument('-a', '--all', action='store_true', help='Show all elements')
parser.add_argument('-r', '--root', action='store_true', help='Show elements at root level')
parser.add_argument('-v', action='store_true', help='Verbose')
parser.add_argument('sourcefile', nargs=1, help='File to parse')
args = parser.parse_args()
And by default, -h and --help are provided:
munchkin:cambx grahamellis$ ./xmlparserdemo -h 6_context.xml
usage: xmlparserdemo [-h] [-a] [-r] [-v] sourcefile
positional arguments:
sourcefile File to parse
optional arguments:
-h, --help show this help message and exit
-a, --all Show all elements
-r, --root Show elements at root level
-v Verbose
Parameters are named within the object returned by the parser, so:
if args.v:
print("Running in verbose mode on file %s " % args.sourcefile[0])
And usage lines generated if the program is run with incorrect arguments:
munchkin:cambx grahamellis$ ./xmlparserdemo -v -all 6_context.xml
usage: xmlparserdemo [-h] [-a] [-r] [-v] sourcefile
xmlparserdemo: error: argument -a/--all: ignored explicit argument 'll'
Complete program using this code [here] ... the program goes on to handle XML data - there's a sample XML file [here] .
Some other articles
Y115 - Additional Python Facilities Some gems from Intermediate Python This article Json load from URL, recursive display, Python 3.4 Running an operating system command from your Python program - the new way with the subprocess module Json is the new marshall, pickle and cPickle / Python Python - an interesting application Handling JSON in Python (and a csv, marshall and pickle comparison) JSON from Python - first principles, easy example Teaching dilemma - old tricks and techniques, or recent enhancements? A demonstration of how many Python facilities work together Python regular expressions - repeating, splitting, lookahead and lookbehind Joining a MySQL table from within a Python program Factory methods and SqLite in use in a Python teaching example Running operating system commands from your Python program Python decorators - your own, staticmethod and classmethod Model - View - Controller demo, Sqlite - Python 3 - Qt4 Connecting Python to sqlite and MySQL databases Regular Expressions in Python Python - what is going on around me? Python - how it saves on compile time Serialization - storing and reloading objects Testing code in Python - doctest, unittest and others Python Regular Expressions A series of tyre damages Ignore case in Regular Expression Regular expressions made easy - building from components Turning objects into something you can store - Pickling (Python) Buffering output - why it is done and issues raised in Tcl, Perl, Python and PHP Sending an email from Python Python - listing out the contents of all variables Python 3000 - the next generation Keeping your regular expressions simple Python to MySQL Splitting the difference What and why for the epoch Examples - Gadfly, NI Number, and Tcl to C interface The elegance of Python Y108 - String Handling Prining a pound sign from Python AND running from the command line at the same time Python formatting update - including named completions This article Python - comparison of old and new string formatters Identifying and clearing denial of service attacks on your Apache server Formatting options in Python Why are bus fares so high? Collections in Python - list tuple dict and string. Formatting output - why we need to, and first Python example Backquote, backtic, str and repr in Python - conversion object to string Teaching dilemma - old tricks and techniques, or recent enhancements? Python string formatting - the move from % to str.format Formatting output in Python through str.format Matching a license plate or product code - Regular Expressions Matching to a string - what if it matches in many possible ways? Python - splitting and joining strings Formatted Printing in Python Running operating system commands from your Python program Regular Expressions in Python Flexible search and replace in Python Pound Sign in Python Program Strings as collections in Python Python Regular Expressions Underlining in Perl and Python - the x and * operator in use Python - formatting objects Regular Express Primer Python - two different splits String duplication - x in Perl, * in Python and Ruby Splitting Pythons in Bradford Matching within multiline strings, and ignoring case in regular expressions Pieces of Python Breaking bread The fencepost problem Python printf Splitting the difference The backtick operator in Python and Perl Y110 - File Handling with in Python - examples of use, and of defining your own context Scons - a build system in Python - building hello world Easy data to object mapping (csv and Python) This article Running an operating system command from your Python program - the new way with the subprocess module Loving programming in Python - and ready to teach YOU how Shell, Awk, Perl of Python? Python or Lua - which should I use / learn? How can I do an FTP transfer in Python? A demonstration of how many Python facilities work together Python - fresh examples from recent courses Old prices - what would the equivalent price have been in 1966? Checking robots.txt from Python Conversion of OSI grid references to Eastings and Northings Reading a file multiple times - file pointers The elegance of Python Relative or absolute milkman