Python                                                          Home : www.sharetechnote.com

 

 

 

 

Python - Command Line Argument

 

If you are at early stage of learning computer programming you may not see such a strong necessity of this kind of function, but as your programming experience gets longer and your skill gets better you would like to your script more flexible and let it work differently based on parameters that user specifies. This is where you see the necessity of Command Line Argument processing.

 

 

Example 01 >

 

Create a file named CommandLineArgTest.py and type in following code

 

import sys

 

print("The name of the script file: ", sys.argv[0])

print("Number of the command line arguments: ", len(sys.argv))

print("The arguments are: " , str(sys.argv))

 

argList = ["apple","banana","strawberry"]

 

i = 0;

for cmd in sys.argv :

   print("Argument[", i, "] = ",cmd)

   i = i + 1

 

You can run the script with the command line argument as shown below.

 

 

Then you should have the result as shown below.

 

 

With the same script, you can pass any number of arguments as shown below (i put different number of space between arguments to show that the number of space between arguments does not matter)