Python - Get input arguments of command line

By xngo on June 25, 2019

The list of command line arguments passed to Python script is stored in sys.argv list. You simply access items of the list to get the informations. sys.argv[0] is the script name. sys.argv[1] is the first argument. sys.argv[2] is the second argument and so on.

Here is an example.

import sys
 
# sys.argv[0] is the script name.
print("This script name is " + sys.argv[0])
 
# 1st argument.
print("1st argument is " + sys.argv[1])
 
# 2nd argument.
print("2nd argument is " + sys.argv[2])
 
# Print all arguments.
print("All arguments are: " + str(sys.argv))

Output

> python py-arguments.py 1st 2nd 3rd
This script name is py-arguments.py
1st argument is 1st
2nd argument is 2nd
All arguments are: ['py-arguments.py', '1st', '2nd', '3rd']

Convert argument to proper datatype

By default, all arguments passed to Python script are returned as strings. Therefore, you have to convert them to the proper datatype before using them. Here is an example.

# Convert to integer.
first_integer = int(sys.argv[1])
add_int = first_integer + 1
print(add_int)
 
# Convert to float.
second_float = float(sys.argv[2])
add_float = second_float + 1.10
print(add_float)

Output

> python py-arguments.py 3  2.11
4
3.21

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.