At Agira, Technology Simplified, Innovation Delivered, and Empowering Business is what we are passionate about. We always strive to build solutions that boost your productivity.

Command Line Arguments in Python

  • By Aishwarya Damani
  • April 1, 2020
  • 1282 Views

Python command-line arguments provide a user-friendly interface to your normal text-based command-line program, same as other graphical user interfaces for applications.

Command-line Argument Uses

Till now we are using the raw input or input method to take input from the command line but this works only while the program/script is running.  But what we are going to discuss is how we are going to run any python program/script from the command line which accepts input with it.
Most Used Module:

  • sys.argv
  • getopt module

ALSO READ: MongoDB In Golang With Examples – A Beginner’s Guide

Sys.argv

It provides functions and variables that are used to manipulate the parts of the Python runtime environment. This module gives access to the variables which are used or maintained by the interpreter and function which interact with the interpreter. Some sample examples are:

  1. List of command-line arguments (sys.argv).
  2. Number of Command line arguments (len(sys.argv)).
  3. Provides name of current script (sys.argv[0]).

Example

Note: Write the below code in a python file as sys argv work only in script file

import sys
n = len(sys.argv)
print("Total arguments passed:", n)
print("\nName of Python script:", sys.argv[0])
print("\nArguments passed:", end = " ")
for i in range(1, n):
    print(sys.argv[i], end = " ")
# Using argparse module :
Sum = 0
for i in range(1, n):
    Sum += int(sys.argv[i])
print("\n\nResult:", Sum)

Command to be executed in terminal:

 $ python3 script-file.py 1 3 6 8 9

Output

Total arguments passed: 6
Name of Python script: script-file.py
Arguments passed: 1 3 6 8 9 
Result: 27

ALSO READ: How To Develop A Healthcare Mobile Application For Hospitals

Getopt

This method is similar to the getopt() function of C. The getopt extends the separation of the given input string by param validation. It accepts both short and long options including a value assignment. This module is required to use the sys module to process data. To use the getopt module we have to remove the first data from the list of command-line arguments.

Example

Note: Write the below code in a python file as sys argv work only in script file

import getopt, sys
argumentList = sys.argv[1:]
options = "hmo:"
long_options = ["Help", "My_file", "Output ="]
try:
    arguments, values = getopt.getopt(argumentList, options, long_options)
    for currentArgument, currentValue in arguments:
        if currentArgument in ("-h", "--Help"):
            print ("Displaying Help")
        elif currentArgument in ("-m", "--My_file"):
            print ("Displaying file_name:", sys.argv[0])
        elif currentArgument in ("-o", "--Output"):
            print (("Enabling special output mode (% s)") % (currentValue))
except getopt.error as err:
    print (str(err))

Command to be executed in terminal:

$ python3 script-file.py -h

Output

Displaying Help
$ python3 script-file.py --help -m

Output:

Displaying Help
Displaying file_name: script-file.py
$ python3 script-file.sh --My_file -o Blue

Output:

Displaying file_name: script-file.py
Enabling special output mode (Blue)

These are the two basic and most used modules for command line arguments in python. But there are some more modules you can go through the official document.
Do you find it interesting? you might also like these articles. Top 10 Best Tech Companies For Employees To Work In The USA In 2020 and Top 10 IT Staffing and Recruiting Agencies in the USA.
If you have a business idea in your mind and searching for a reliable web development company, you are in the right place. Hire the best web developers in the industry from Agira technologies.

Looking for a Tech partner to dominate the digital world?

Aishwarya Damani

An aspiring adolescent started her career as Software Engineer Trainee and slowly she's mastering all the rising technologies like Nodejs, Express.js, React.js, MongoDB, Sails. On the other hand, a perfect decision maker who is passionate about coding. Wait! there's half a lie! Yeah, this crazy foodie has an intense long lasting affair on trying different foods & exploring places.