The Ultimate Guide to Command Line Arguments in Python Scripts

Moez Ali
7 min readApr 18, 2023

A Comprehensive beginner friendly tutorial on using command-line arguments in Python

Photo by Oskar Yildiz on Unsplash

Introduction

Command line arguments are a powerful way to pass parameters to a program when it is executed. They allow users to customize the behavior of the program without modifying its source code. Command-line arguments are used extensively in the Unix/Linux command-line interface and are also commonly used in scripting languages like Python.

Compared to other types of user input like prompts and web forms, command-line arguments are more efficient and can be automated easily. They can also be used to run scripts in batch mode, without the need for user interaction.

Basic Syntax

In Python, command-line arguments are accessed through the sys.argv list. The first item in the list is always the name of the script itself, and subsequent items are the arguments passed to the script.

Here is an example script that prints out the command line arguments:

import sys

for arg in sys.argv:
print(arg)

If you save this script as test.py, you can run it from the command line with arguments like this:

python test.py arg1 arg2 arg3

--

--

Moez Ali
Moez Ali

Written by Moez Ali

Data Scientist, Founder & Creator of PyCaret

No responses yet