Retrieving the CommandLine in Python scripts

Using command lines in Python scripts is fairly straightforward. The script below works in Python 2.8 or higher. There are more options and alternatives to retrieve and process command line, but let’s stick to the basics for now.

import argparse as args

parser = args.ArgumentParser(description='Analyzing commandline...')
parser.add_argument("-b", "--blockfile"
                    , default="blocklist.txt"
                    , required=False
                    , help="File containing the sites that should be blocked. One site per line.")

parsed_args = parser.parse_args()

print(parsed_args.blockfile)

Explicando o fonte acima:

  • First we import the class (argparse) that renders the lines of command;
  • Then we create a Parser to process the command line. The ‘description’ attribute will be displayed when this row is processed;
  • The next step is to add each argument that you want to receive in your script;
    • The first two attributes are name and flag of the argument. Any one of these values can be used on the command line to define the value;
    • default is the… default value for this argument, if it is omitted;
    • required sets whether the argument is mandatory or not. If it is required, the default attribute is ignored;
    • help is the text that will be displayed. describing this argument, when the script is run with-h (or–help);
  • Once all the arguments are set, just use the function parse_args() to retrieve the values passed on the CommandLine. This function will return a variable with with all the argument values.

This will be the result of the above code, if the script is executed with no arguments:

python demo.py

blocklist.txt

…if we change de required attribute to true and still don’t pass any arguments:

python demo.py

usage: PyGuestWatcher.py [-h] -b BLOCKFILE
PyGuestWatcher.py: error: the following arguments are required: -b/--blockfile

… running the script, passing the argument using the name (-b) and the flag (–blockfile):

python demo.py -b 'foo.bar'

'foo.bar'
python demo.py --blockfile 'foo.bar'

'foo.bar'

 

Reference:

The following two tabs change content below.
Software Architect and Backend Developer (almost Fullstack), I usually work with C#, PowerShell, Python, Golang, bash and Unity (this one is more for a hobby). I'm always looking for something new to learn, adding new tools to my utility belt.
Posted in Dev, Python and tagged , , , , .