Retrieving the CommandLine in Python scripts

Retrieving the CommandLine in Python scripts


Dive into the world of Python scripting and command line processing with a simple, yet comprehensive guide. Whether you’re navigating the basics or looking to streamline your projects, this post has you covered. From importing argparse to parsing arguments and setting conditions, boost your skills in no time. Embrace the power of command line in Python, and let’s decode the essentials together.

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()


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:



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


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

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

python -b ''

python --blockfile ''