Code has been added to clipboard!

Writing and Reading Python Command Line Arguments

Reading time 2 min
Published Feb 20, 2020
Updated Feb 20, 2020

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
  • Simplistic design (no unnecessary information)
  • High-quality courses (even the free ones)
  • Variety of features
Main Features
  • Nanodegree programs
  • Suitable for enterprises
  • Paid certificates of completion
  • Professional service
  • Flexible timetables
  • A variety of features to choose from
Main Features
  • Professional certificates of completion
  • University-level courses
  • Multiple Online degree programs
  • Great user experience
  • Offers quality content
  • Very transparent with their pricing
Main Features
  • Free certificates of completion
  • Focused on data science skills
  • Flexible learning timetable

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:

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 argparse.
  • 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.

Latest Udacity Coupon Found:



Udacity Black Friday Offer

The best time to save on Udacity courses is now - follow this coupon to access a 75% Udacity Black Friday discount & enjoy learning at a very low cost!

Expiration date: 11/03/2021
3176 People Used
Only 97 Left