Web Development Course:
TL;DR – Python command line arguments represent input that gets passed to the executed script.
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.
||Stores Python command line arguments in a list. To access and read them as strings, use
||Allows you to parse command line parameters. Similar to the
||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:
import sys print (sys.argv)
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 by
- 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.