Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App

Related Articles

Python | Set 6 (Command Line and Variable Arguments)

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

Previous Python Articles (Set 1 | Set 2 | Set 3 | Set 4 | Set 5
This article is focused on command line arguments as well as variable arguments (args and kwargs) for the functions in python.

Command Line Arguments

Till now, we have taken input in python using raw_input() or input() [for integers]. There is another method that uses command line arguments. The command line arguments must be given whenever we want to give the input before the start of the script, while on the other hand, raw_input() is used to get the input while the python program / script is running.
For example, in the UNIX environment, the arguments ‘-a’ and ‘-l’ for the ‘ls’ command give different results.
The command line arguments in python can be processed by using either ‘sys’ module or ‘argparse’ module. 


# Python code to demonstrate the use of 'sys' module
# for command line arguments
import sys
# command line arguments are stored in the form
# of list in sys.argv
argumentList = sys.argv
print (argumentList)
# Print the name of file
print (sys.argv[0])



NOTE : The above code runs only on command line. We need to fire the below command given that the program is saved as 
python test 123 

Please note the following points about the above program : 

  • The sys.argv takes the command line arguments in the form of a list.
  • The first element in the list is the name of the file.
  • The arguments always come in the form of a string even if we type an integer in the argument list. We need to use int() function to convert the string to integer.
My Personal Notes arrow_drop_up
Last Updated : 25 Jan, 2022
Like Article
Save Article
Similar Reads
Related Tutorials