Prompt for user input & read command-line arguments in Python

In this Python tutorial, we will learn how to prompt for user input and read command-line arguments in Python Programming language. This enhances the productivity and functionality, when we can directly take the input from user while executing the program.

Table Of Contents

Introduction

The Commad-line arguments, are the arguments which are passed with the program in the command line as an arguments. It is similar to the arguments that we pass to any function while calling it. This argument is passed to the program in the Command Line, at the time of execution of the Program.

Example : python code.py argument1 argument2

User Input

For user input in Python Programming language, we use the input() method. In which we can pass a string which will prompt for user input. See the example below:

Advertisements

CODE :

# taking an user input
name = str(input('Enter Your name..'))

print('Your name is:', name)

OUTPUT :

Enter Your name..Python
Your name is: Python

In the above code and output, we have an example for user input in Python Programming language. Also you may notice str() has been used, with input() passed inside of it. This is because whatever the user will input will be type casted to class str and then it will be stored to name variable.

Now let’s learn How to prompt for user input and read command-line arguments?

Method 1 : Using the Sys module

First we will be using sys module, which comes pre-installed with Python Programming language, to propmt for user input and read command-line arguments. This module in python programming language is widely used to interact with the system. It provides various function and modules that can communicate with the Python Interpreter and also used to manipulate python runtime environment.

See the example code below and then we will discuss the program and sys module.

CODE :

import sys

first_name = sys.argv[1]
last_name = sys.argv[2]

print("Full Name: ", first_name + ' ' + last_name)

COMMAND :

python main.py Virat Kohli

OUTPUT :

Full Name: Virat Kohli

In the above code, we have used the command line to run the python program main.py and used two arguments at the time of execution of the program. sys.argv reads the arguments which are passed to the Python at the time of execution of the code. Here we have used sys.argv[] with index number. Index number denotes the argument passed, like [1] denotes the first argument which is passed to the python run time. Whereas, [0] is reserved for script file name.

Method 2 : Using argparse module

Another method that we can use to prompt for user input and read command-line arguments is using the argparse module, which comes pre-installed with the Python Programming Language. This module in Python, provides a great environment of command line interaction. The argparse module generates suitable error messages if any wrong argument is provided to the program at the time of execution.

First we have to create a Parser object, with the command argparse.ArgumentParser(). It recieves many arguments such as prog which stores the name of the program. Default is sys.argv[0] which holds the name of the executed program.

Next, we will provide it with all the necessary information like, which arguments can be passed with this program. For this, we will use add_argument() method or Parser object. In this, we will pass the argument name, and help information, in case argument is not provided.

Next we will parse the Arguments which will be provided with the program. For this we will use parse_args() method. It will check if all the required arguments are provided or not. For arguments, which are not provided, it will display the error message. If all required arguments are provided, then it will populate their value in the args object, and returns the args object.

Let’s see an example,

import argparse

# creating a parse object
parser = argparse.ArgumentParser()

# adding arguments
parser.add_argument("first_name",help="Enter Your First Name.")
parser.add_argument("second_name",help="Enter Your Second Name.")

# parsing arguments
args = parser.parse_args()

print('Full name is: ',args.first_name + ' ' + args.second_name)

COMMAND :

python main.py Virat Kohli

Here our first argument is virat and second argument is kohli.

OUTPUT :

Full name is: Virat Kohli

In the above example, the argparse module has been used to read command line arguments in Python.

If we want to know the usage details of this script then we can execute it with the --h option. For example,

python main.py -h

It will display the proper help details. Basically the arguments required, and thier details, that we registered with the arguments. Output will be,

usage: main.py [-h] first_name second_name

positional arguments:
  first_name   Enter Your First Name.
  second_name  Enter Your Second Name.

optional arguments:
  -h, --help   show this help message and exit

Method 3 : Using getopt module

Another method we can use to prompt for user input and read command-line argument is using the getopt module. It is a C style parser for command line arguments/options. This module comes pre-install with Python Programming language. We will be using sys.argv also. See the example code and output then we will discuss the program.

CODE :

import getopt
import sys

first_name = None
Second_name = None

# sys.argv to reads the argument.
argv = sys.argv[1:]

# returns two elements, storing return values.
opts,args = getopt.getopt(argv,"f:e:")

for opt,arg in opts:
    if opt in ['-f']:
        first_name = arg
    elif opt in ['-e']:
        Second_name = arg

print('Full Name: ', first_name + ' ' + Second_name)

COMMAND :

python main.py -f Virat -e Kohli

OUTPUT :

Full Name: Virat Kohli

In the above example, we have used the getopt module along with sys.argv to prompt user input and read command line arguments.

So here we have getotp.getotp() function which also is the main function of this method. This function receives three parameters:

  • args: Arguments which needs to be passed.
  • options : String or identifiers which separates or identifies the arguments. Here we have used “f and e”.
  • long_options : Optional, this specifies the arguments which is followed by an equal to sign(=).

This function returns two elements:

  • list of option and value
  • list of arguments remaining after slicing with the help of optional parameter.

In this method first we slice the arguments with the help of sys.argv, then we provide the required parameters in the getopt() function and this returns two tuples inside the list, separated by the options argument. Then we have used for loop and if-elif statements to assign the values.

Summary

Today we learned how to prompt for user input and read command-line arguments? For this we have used three different methods/modules. Most easy and widely used is the sys module, which is mainly used to interact with the Command Line Interface.

Make sure to practice with above mentioned examples, to have a better understanding of this concept. Thanks.

Advertisements

Thanks for reading.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top