TL;DR – Python command line arguments represent input that gets passed to the executed script.
Contents
Understanding command line
Command line and its arguments are not specific to Python – you can find them in most programming languages, including C, C++, PHP, Java and others. Simply put, it's a way to manage a program script from outside by typing the script name and the input arguments into the command line prompt when trying to execute that particular script.
In Python, command line arguments can be used to:
- Adjust the operation of a certain program
- Define a source of information
- Specify a destination for the information
Working with command line arguments: Python modules
Unlike in Java and C-based languages, you need to use a specific module to work with Python command line arguments.
Module | Description |
---|---|
sys |
Stores Python command line arguments in a list. To access and read them as strings, use sys.argv . |
getopt |
Allows you to parse command line parameters. Similar to the getopt() function in C and recommended when you need to include options. |
argparse |
Allows you to parse command line parameters and offers extra options: you can specify the data type and the default value, add a help message, etc. |
If there are no Python command line arguments, sys.argv
will simply return the name of the script:
Python command line arguments: useful tips
- In older Python versions, you could also use
optparse
. However, you it has been deprecated since Python 3.2 and replaced byargparse
. - Don't mistake command line options with command line arguments! Python command line options are also called switches or flags and change the way Python commands operate.
- To avoid execution errors, be extra careful with spacing and line indentation.