Python Use Command Line Arguments: A Beginner Guide – Python Tutorial

By | December 6, 2019

As to some python applications, we often may use some command line arguments. As to python applications,  how do they get and parse these arguments? In this tutorial, we will discuss this topic for python beginners.

We may run a python script with some command line arguments like below:

python -i demo.png -o demo.eps

How to get and parse command line arguments in python?

As to python, we can use sys.argv to get these arguments.

Here is an example.

import sys

print('Arguments:', len(sys.argv))

for i in sys.argv:

The result is:

<class 'list'>
Arguments: 5

From result we can find:

1. As to command line arguments, python script name is also an argument, which is the first one.

2.sys.argv is a python list, which contains all command line arguments.

3.All command line arguments are separated by blank space, sys.argv will split and save them.

python command line arguments examples

As a python programmer, if we need use command line arguments, we can get all of them by sys.argv.