How To Get Command Line Arguments In Python

Through the argv attribute of Python sys module, you can get the command line parameters of running Python program. The attribute value is a list, and the relationship between list elements and running parameters is as follows.

$python python-program-file param1 param2 ......

'''
python-program-file: for example test.py, it is the first element in list argv (argv[0]).

param1: the second element in list argv (argv[1]).

param2: the third element in list argv (argv[2]).

......

'''

Therefore, if you need to get the parameters passed in when running a Python program, you can use argv [1], argv [2] to get it. Save below source code in a Python file test.py.

from sys import argv

# Get argv length.
args_len = len(argv)

# Print argv length.
print(args_len)

# Traverse each element of the argv list and print out it's value.
for arg in argv:
    print(arg)

Now run the above python file with the command python test.py p1 p2 in a terminal, you will get beow output.

$ python test.py p1 p2
3
test.py
p1
p2

If a parameter itself contains a space, it should be enclosed in double quotation marks (“), otherwise, Python will treat the space as a parameter separator instead of the parameter itself.

# Use double quotation to wrap input parameters which has whitespace in it. 
$ python test.py "hello world"
2
test.py
hello world

$ python test.py hello world
3
test.py
hello
world

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Clicky