How to access command-line arguments in Python

By IncludeHelp Last updated : February 8, 2024

The command-line arguments are the arguments passed during the execution of a program with the program/script name. In this tutorial, we will learn how can we access these command-line arguments in Python.

Problem statement

Write a Python program to access command-line arguments.

Accessing command-line arguments

In Python, you can use the `argv` attribute of the `sys` module to access command-line arguments provided program's execution. The `sys.argv` stores the list of the arguments provided by the command prompt.

Syntax

sys.argv[0] # to get first argument
sys.argv[1] # to get second argument

Python program to access command-line arguments

Let suppose, file's name is main.py

# Importing sys Module
import sys

# The first element at index 0 is
# the program/script name
prg_name = sys.argv[0]
print("Program/Script Name :", prg_name)

# Now, getting rest of two arguments
arg1 = sys.argv[1]
arg2 = sys.argv[2]

print("The Command-line arguments are :", arg1, "and", arg2)

Output

The output of the above program is:

Command:
python main.py 10 20

Output:
Program/Script Name : main.py
The Command-line arguments are : 10 and 20

Access all command-line arguments

You can access all arguments except the script name by using the list comprehension statement sys.argv[1:], it will return a list of all arguments passed by the command prompt.

Example

# Importing sys Module
import sys

print("Command-line arguments :", sys.argv[1:])

The output of the above program is:

Command:
python main.py 10 20 30 Hello World

Output:
Command-line arguments : ['10', '20', '30', 'Hello', 'World']

Iterative through all command-line arguments

To iterate through all command-line arguments in Python, you can use for in loop with list comprehension (sys.argv[1:]).

Example

# Importing sys Module
import sys

# Iterative through all command-line 
# arguments
for arg in sys.argv[1:]:
    print(arg)

The output of the above program is:

Command:
python main.py 10 20 30 Hello World

Output:
10
20
30
Hello
World
 
 

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.