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
Pros Main Features
- Easy to use with a learn-by-doing approach
- Offers quality content
- Gamified in-browser coding experience
- The price matches the quality
- Suitable for learners ranging from beginner to advanced
- Free certificates of completion
- Focused on data science skills
- Flexible learning timetable
Pros Main Features
- Simplistic design (no unnecessary information)
- High-quality courses (even the free ones)
- Variety of features
- Nanodegree programs
- Suitable for enterprises
- Paid Certificates of completion
Pros Main Features
- A wide range of learning programs
- University-level courses
- Easy to navigate
- Verified certificates
- Free learning track available
- University-level courses
- Suitable for enterprises
- Verified certificates of completion
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.