Oct. 01, 2012

How to use sys.argv in Python

What is sys.argv?

sys.argv is a list in Python, which contains the command-line arguments passed to the script. 

With the len(sys.argv) function you can count the number of arguments. 

If you are gonna work with command line arguments, you probably want to 
use sys.argv. 

To use sys.argv, you will first have to import the sys module. 


To show how this works. 

(Remember that sys.argv[0] is the name of the script.
import sys
print "This is the name of the script: ", sys.argv[0]
print "Number of arguments: ", len(sys.argv)
print "The arguments are: " , str(sys.argv)


This is the name of the script:  sysargv.py
Number of arguments in:  1
The arguments are:  ['sysargv.py']

If I run it again with additional arguments, I will get this output:

This is the name of the script:  sysargv.py
Number of arguments in:  3
The arguments are:  ['sysargv.py', 'arg1', 'arg2']

Share this article

Recommended Python Training – DataCamp

For Python training, our top recommendation is DataCamp.

Datacamp provides online interactive courses that combine interactive coding challenges with videos from top instructors in the field.

Datacamp has beginner to advanced Python training that programmers of all levels benefit from.


Download Our Free Guide To Learning Python

* indicates required

Read more about:
Disclosure of Material Connection: Some of the links in the post above are “affiliate links.” This means if you click on the link and purchase the item, I will receive an affiliate commission. Regardless, PythonForBeginners.com only recommend products or services that we try personally and believe will add value to our readers.