Download Command line arguments

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Command line arguments
I
When a Python script runs it gets a list of command line
arguments
I
Command line arguments allow for more than ‘default’
behaviour for a script
I
The
sys
module provides access to that list as
sys.argv
The sys.argv list
#!/usr/bin/python
import sys
print "this script is:", sys.argv[0]
print "my command line is:", sys.argv[1:]
I
The name
I
The first item of the sys.argv list is the name of the running
program (the script).
I
The command line arguments (if any) start from
onwards.
argv
originally meant argument vector.
sys.argv[1:]
Reading arguments from sys.argv
I
If we have made our script runnable by including the
#!/usr/bin/python line
I
and setting execute permissions with chmod a+x
I
we can count the number of command line arguments we are
given, it is len(sys.argv) - 1
I
and we can read them to give our program parameters (see
next slide).
I
Command line arguments are to a program what parameters
are to a function: they are pieces of data to work with
I
but they are only strings (no lists or files or dictionaries).
Count lines of a file
count lines cmdline.py
#!/usr/bin/python
import sys
if len(sys.argv) != 2:
sys.stderr.write(’Usage: %s <filename>\n’ % (sys.argv[0]))
sys.exit(1)
input_filename = sys.argv[1]
input_file = open(input_filename)
count = 0
for line in input_file:
count += 1
print "line count:", count
I
I
I
If we’re using sys.argv, we need to check its length, else we
might get a IndexError
If we don’t have the right command line arguments we tell the
user (through a message written to sys.stderr) and exit straight
away (using sys.exit)
The sys.exit function takes an “exit code” as its single
parameter. By convention, an exit code of 0 means everything
completed ok, any other number shows that an error occurred.
When in doubt: use argparse
I
Handling sys.argv ourselves is fine for simple cases, but since
command line arguments are a common part of programs,
Python provides several modules for dealing with them.
I
Unless you’re using Python older than version 2.7, the best
module to use is argparse
count lines argparse.py
#!/usr/bin/python
import argparse
parser = argparse.ArgumentParser(description=’Count the lines in a file’)
parser.add_argument(’input_filename’, help=’Input file’)
args = parser.parse_args()
input_file = open(args.input_filename)
count = 0
for line in input_file:
count += 1
print "line count:", count
The basic elements of argparse
I
First import the module with
I
Then get an argument parser. This is an object of type
argparse.ArgumentParser so we make one of those:
import argparse
parser = argparse.ArgumentParser(description=’Some text to describe our program’)
I
We add the descriptions of the arguments we need to parse
with the add_argument method of our parser object. This method
has defaults for most of its parameters, but we need to supply
at least an argument name, and it is a good idea to provide
some help text to explain the use of the argument:
parser.add_argument(’some_name’, help=’Describe what some_name does’)
I
Finally we tell the parser to process the argument list. By
default this reads sys.argv and it returns a namespace object
that we can use to get at the argument values.
args = parser.parse_args()
print args.some_name
What argparse does right
I
The argparse module handles counting of arguments and
printing a useful error message if the command line arguments
are incorrect.
I
In addition to strings, it can process command line arguments
as integers, file and boolean types.
I
It can handle both options (e.g. -l) and positional arguments.
I
Finally,
I
Read about argparse at this tutorial and the official
documentation.
argparse
can also handle optional arguments.
Handling non-string arguments
I
The add_argument method of the argparse takes an optional type
parameter to specify the type that the argument should be
converted to:
parser.add_argument(’line_num’, type=int, help=’Line number to read from file’)
I
The argparse.FileType class is used to specify that the argument is
the name of a file that should be opened:
parser.add_argument(’input_file’, type=argparse.FileType(), help=’Input file’)
parser.add_argument(’output_file’, type=argparse.FileType(’w’), help=’Out file’)
I
Boolean types can be used for options, using a combination of
action and default parameters to add_argument:
parser.add_argument(’--zero_based’, action=’store_true’, default=False)
Non-string arguments: an example
read linenum.py
#!/usr/bin/python
import argparse
import sys
parser = argparse.ArgumentParser(description=’Read the specified line from a file’)
parser.add_argument(’--zero_based’, ’-z’,
default=False, action=’store_true’,
help=’Line numbers start from zero’)
parser.add_argument(’line_num’, type=int, help=’The line number to read’)
parser.add_argument(’in_file’, type=argparse.FileType(), help=’Input file’)
parser.add_argument(’out_file’, type=argparse.FileType(’w’), help=’Out file’)
args = parser.parse_args()
if args.zero_based:
count = 0
else:
count = 1
for line in args.in_file:
if count == args.line_num:
args.out_file.write(line)
break
count += 1
args.out_file.close()
args.in_file.close()
Optional and list arguments
I
The nargs parameter to add_argument changes how words are taken
from the command line and returned as arguments.
I
If
nargs
is a number, a list is returned:
parser.add_argument(’read_files’, nargs=2, type=argparse.FileType(), help=’...’)
I
If nargs is ‘?’, the argument is optional. This can be used to
allow optional input or output files:
parser.add_argument(’out_file’, nargs=’?’, type=argparse.FileType(’w’),
default=sys.stdout, help=’Output file’)
I
If nargs is ‘*’, all the remaining words are taken from the
command line and returned as a list:
parser.add_argument(’in_files’, nargs=’*’, type=argparse.FileType(),
help=’Files to read’)
List arguments: an example
count files.py
#!/usr/bin/python
import argparse
parser = argparse.ArgumentParser(description=’Count the lines in a list of files’)
parser.add_argument(’input_files’, nargs=’*’, type=argparse.FileType(),
help=’Files to read’)
args = parser.parse_args()
total_lines = 0
for in_file in args.input_files:
file_line_count = 0
for line in in_file:
total_lines += 1
file_line_count += 1
print in_file.name, "has", file_line_count, "lines"
print "total lines:", total_lines
In Conclusion
I
The sys.argv list provides a list of command line arguments.
The first element of the list is the name of the currently
running program.
I
For all except the simplest cases, it is easier to use the argparse
module to parse (i.e. interpret) command line arguments.
I
By default, argparse treats command line arguments as strings,
but it can convert arguments into different types (such as int
and file types).
I
Arguments whose names start with ‘-’ and ‘–’ are short and
long options respectively. By contrast, other arguments are
called positional arguments and are the ‘main’ arguments of
the program, whereas options modify how the positional
arguments are interpreted.
I
Optional arguments and list arguments can be parsed using
the nargs parameter of the add_argument method.