We will show how we can pass arguments in the script via the command line instead of having to get user input. The simplest way to do that is by working with the sys module and the sys.argv attribute and a more advanced way is to work with the argparse module and the argparse.ArgumentParser class
sys.argv
example
The list of command-line arguments passed to a Python script. argv[0]
is the script name (it is operating system dependent on whether this is a full pathname or not). If the command was executed using the -c
command line option to the interpreter, argv[0]
is set to the string '-c'
. If no script name was passed to the Python interpreter, argv[0]
is the empty string. Let’s provide an example of the myargv.py
script. Note that the input arguments start from index 1 and not 0
import sys print(f"Positional arguments: {sys.argv[1:]}") print(f"First argument: {sys.argv[1]}")
Now, we will run the script three times. The first time we will give one argument “predictive”, the second time we will give two arguments, “predictive hacks” and the third time we not give any argument.
As we can see it worked as we expected for the first two cases, but for the third case, we received an error (IndexError) when we asked to get the first argument, however, when we asked for the positional argument, we received an empty list []
. Finally, keep in mind that the positional arguments are based on spaces unless we explicitly wrap the argument in quotes.
argparse
example
The add_argument() method
ArgumentParser.
add_argument
(name or flags…[, action][, nargs][, const][, default][, type][, choices][, required][, help][, metavar][, dest])
Define how a single command-line argument should be parsed. Each parameter has its own more detailed description below, but in short they are:
- name or flags – Either a name or a list of option strings, e.g.
foo
or-f, --foo
. - action – The basic type of action to be taken when this argument is encountered at the command line.
- nargs – The number of command-line arguments that should be consumed.
- const – A constant value required by some action and nargs selections.
- default – The value produced if the argument is absent from the command line and if it is absent from the namespace object.
- type – The type to which the command-line argument should be converted.
- choices – A container of the allowable values for the argument.
- required – Whether or not the command-line option may be omitted (optionals only).
- help – A brief description of what the argument does.
- metavar – A name for the argument in usage messages.
- dest – The name of the attribute to be added to the object returned by
parse_args()
.
name or flags
The add_argument()
method must know whether an optional argument, like -f
or --foo
, or a positional argument, like a list of filenames, is expected. The first arguments passed to add_argument()
must therefore be either a series of flags, or a simple argument name
We will provide an example of argparse
where the script will take as input the file name and the number of printed lines and it will return the lines in reverse order.
The myfile.txt
is the following:
1.George 2.Jim 3.Maria 4.Joe 5.Steve 6.Stella
and the myargparse.py
script is the following.
import argparse parser = argparse.ArgumentParser(description='Read a file in reverse') parser.add_argument('filename', help='the file to read') parser.add_argument('--limit', '-l', type=int, help='the number of lines to read') args = parser.parse_args() with open(args.filename) as f: lines = f.readlines() lines.reverse() if args.limit: lines = lines[:args.limit] for l in lines: print(l.strip())
We will give as arguments the myfile.txt
and limit 3
.
References
[1] Linux Academy