Understanding Command Line Arguments in Python

Read it in 8 Mins

Last updated on
14th Sep, 2022
Published
03rd Jul, 2020
Views
9,056
Understanding Command Line Arguments in Python

Command Line argument is a way of managing the script or program externally by providing the script name and the input parameters from command line options while executing the script. Command line arguments are not specific just to Python programming. These can be found in other programming languages like C, C# (C sharp), C++, PHP, Java, Perl, Ruby and Shell scripting. Arguments and parameters are used extensively and a hands-on course on data science with Python will help you understand the use of command line arguments and other useful concepts such as what is markdown etc .  

Don't forget to check out the use of Self in Python.

How to use sys.argv in Python

The sys module is one of the common and frequently used modules in Python. In this article, we will walk you through how to use sys argv python module. We will learn about what argv[0] and sys.argv[1] are and how they work. We will then go into how to parse Command Line options and arguments, the various ways to use sys argv and how to pass command line arguments in Python 3.x

Understanding sys.argv with examples  

sys.argv is a list in Python that contains all the command-line arguments passed to the script. It is essential in Python while working with Command Line arguments. Let us take a closer look with sys argv python example below. 

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

import sys
print ("Number of arguments:", len(sys.argv), "arguments")
print ("Argument List:", str(sys.argv))
$ python test.py arg1 arg2 arg3
Number of arguments: 4 arguments.
Argument List: ['test.py', 'arg1', 'arg2', 'arg3']

Module name to be used while using sys.argv 

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

What is argv[0]? 

Remember that sys.argv[0] is the name of the script. 

Here – Script name is sysargv.py 

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:  1                                                                                                
The arguments are:  ['sysargv.py']

What is "sys. argv [1]"? How does it work? 

When a python script is executed with arguments, it is captured by Python and stored in a list called sys.argv. 

So, if the below script is executed: 

python sample.py Hello Python 

Then inside sample.py, arguments are stored as: 

  • sys.argv[0] == ‘sample.py’ 
  • sys.argv[1] == ‘Hello’ 
  • sys.argv[2] == ‘Python’

Here, sys.argv[0] is always the filename/script executed and sys.argv[1] is the first command line argument passed to the script.

Parsing Command Line options and arguments  

Python provides a module named as getopt which helps to parse command line options and arguments. It provides a function – getopt, which is used for parsing the argument sequence:sys.argv.

Below is the syntax: 

getopt.getopt(argv, shortopts, longopts=[]) 
  • argv: argument list to be passed.
  • shortopts: String of short options as list. Options in the arguments should be followed by a colon (:)
  • .longopts: String of long options as list. Options in the arguments should be followed by an equal sign (=). 
import getopt
import sys
 
first =""
last =""
argv = sys.argv[1:]
try:
    options, args = getopt.getopt(argv, "f:l:",
                               ["first =",
                                "last ="])
except:
    print("Error Message ")
 
for name, value in options:
    if name in ['-f', '--first']:
        first = value
    elif name in ['-l', '--last']:
        last = value
 
print(first + " " + last)

Output:

(venv) C:\Users\Nandank\PycharmProjects\DSA\venv>python getopt_ex.py -f Knowledge -l Hut
Knowledge Hut
(venv) C:\Users\Nandank\PycharmProjects\DSA\venv>python getopt_ex.py --first Knowledge –last Hut
Knowledge Hut

What are command line arguments? Why do we use them? 

Command line arguments are params in Python passed to a program/script at runtime. They provide additional information to the program so that it can execute.

It allows us to provide different inputs at the runtime without changing the code. 

Here is a script named as argparse_ex.py: 

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-n", "--name", required=True)
args = parser.parse_args()
print(f'Hi {args.name} , Welcome ')

Here we need to import argparse package 

Then we need to instantiate the ArgumentParser object as parser. Then in the next line, we add the only argument, --name . We must specify either shorthand (-n) or longhand versions (--name)  where either flag could be used in the command line as shown above. This is a required argument as mentioned by required=True

Output:  

(venv) C:\Users\Nandank\PycharmProjects\DSA\venv>python argparse_ex.py --name Nandan 
Hi Nandan , Welcome 
(venv) C:\Users\Nandank\PycharmProjects\DSA\venv>python argparse_ex.py -n Nandan 
Hi Nandan , Welcome 

The example above must have the --name or –n option, or else it will fail.

(venv) C:\Users\Nandank\PycharmProjects\DSA\venv>python argparse_ex.py --name  
usage: argparse_ex.py [-h] --name NAME
argparse_ex.py: error: the following arguments are required: --name

Passing command line arguments in Python 3.x 

Here are the points you need to keep in mind will executing py passing.

  • argv represents an array having the command line arguments of thescript . 
  • Remember that here, counting starts fromzero [0], not one (1). 
  • To use it, we first need to import sys module (import sys). 
  • The first argument, sys.argv[0], is always the name of the script and sys.argv[1] is the first argument passed to the script. 

Here, we need to slice the list to access all the actual command line arguments. 

import sys
if __name__ == '__main__':
    for idx, arg in enumerate(sys.argv):
       print("Argument #{} is {}".format(idx, arg))
    print ("No. of arguments passed is ", len(sys.argv))

Output:

(venv) C:\Users\Nandank\PycharmProjects\DSA\venv\Scripts>python argv_count.py Knowledge Hut 21 
Argument #0 is argv_count.py 
Argument #1 is Knowledge 
Argument #2 is Hut 
Argument #3 is 21 
No. of arguments passed is  4

Below script - password_gen.py is used to generate a secret password by taking password length as command line argument.

import secrets , sys, os , string
''' This script generates a secret password using possible key combinations'''
''' Length of the password is passed as Command line argument as sys.argv[1]'''
char = string.ascii_letters+string.punctuation+string.digits
length_pwd = int(sys.argv[1])
 
result = ""
for i in range(length_pwd):
    next= secrets.SystemRandom().randrange(len(char))
    result = result + char[next]
print("Secret Password ==" ,result,"\n")

Output:

(venv) C:\Users\Nandank\PycharmProjects\DSA\venv\Scripts>python password_gen.py 12
Secret Password == E!MV|,M][i*[

Key takeaways 

Let us summarize what we've learnt so far. We have seen how to use the sys module in Python, we have looked at what areargv[0] and sys.argv[1] are and how they work, what Command Line arguments are and why we use them and how to parse Command Line options and arguments. We also dived into multiple ways to use argv and how to pass command line arguments in Python 3.x

Hope this mini tutorial has been helpful in explaining the usage of sys.argv and how it works in Python. Be sure to check out KnowledgeHut applied data science with python specialization and don't forget to practice with your code! 

FAQs

1. How do I use SYS argv in Python script? 

To use, sys.argv in a Python script, we need to import the sys module into the script. Like we import all modules, "import sys" does the job. Ideally, we want this at the top of the script, but anywhere before we use the sys.argv functions should still work.

2. What is the data type of the elements of SYS argv? 

Elements of sys.argv is a Python list, all command-line arguments are passed into it in the correct order.

3. What are command line arguments in Python?

Command-line arguments are arguments passed into a Python script through the terminal window. We usually apply them while we're executing a script, with each argument being separated by a space.

For example,

pythonscript.py argument1 arg2 a3

Profile

Nandan Kumar

Author

QA Automation Architect having 12+ Years of experience in UI , Backend and Database testing ( Selenium, Cucumber, Gherkins, Protractor, TestNG) having strong Python/Java Coding skills. Strong experience in Devops/QAops , MongoDB and Certified AWS Solution Architect.


Strong Problem solver having worked on multiple domains: Media and TV/Video Streaming, Investment Banking, E-Commerce/Payments and Cloud Security /Networking/SaaS/IaaS/PaaS.