🚨 Time is Running Out: Reserve Your Spot in the Lucky Draw & Claim Rewards! START NOW

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
  • 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
Main Features
  • Free certificates of completion
  • Focused on data science skills
  • Flexible learning timetable
  • 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
  • Easy to navigate
  • No technical issues
  • Seems to care about its users
Main Features
  • Huge variety of courses
  • 30-day refund policy
  • Free 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:

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.