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. 

Example

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)

Output

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']

Recommended Python Training – Treehouse

Treehouse For Python training, our top recommendation is Treehouse.

Treehouse is an online training service that teaches web design, web development and app development with videos, quizzes and interactive coding exercises.

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



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.