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.

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:

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



The following two tabs change content below.
Breno RdV
Please allow me to introduce myself...I'm a former psychologist, with almost a decade worth of experience in Human Resources and People Management. Now a developer/software analyst working with PowerBuilder, C#, PowerShell and currently expanding to the world of Python, Xamarin, PHP Angular and (why not?) Unity.
Breno RdV

Latest posts by Breno RdV (see all)



Posted in Dev, Python and tagged , , , , .