How to Get User Input From CLI in Python?

In Python, you can get user input via command-line arguments in the following ways:

  1. Using sys.argv;
  2. Using argparse.

Using sys.argv

Using sys.argv gives you a very simple way of getting user input via command-line scripts. It is essentially a list in Python that contains command-line arguments, where:

  1. The first element in the list (i.e. sys.argv[0]) is the script name, and;
  2. The following elements are the arguments passed to the script.

For example:

# script.py
import sys

if len(sys.argv) != 2:
    print("Usage: python script.py <argument>")
    sys.exit(1)

arg = sys.argv[1]

print(f"Argument provided: '{arg}'")

You can run this script in the following way:

python script.py foobar # "Argument provided: 'foobar'"

Please note that when using sys.argv, it's essential to consider error handling, such as checking if the required number of arguments is provided, to prevent index errors.

Using argparse

The argparse module is very versatile. It provides a more structured and user-friendly way to handle command-line arguments than using sys.argv. For instance, it allows you to define the arguments, their types, help messages, and more.

You can get user input using the argparse module in the following way:

import argparse

parser = argparse.ArgumentParser(description='a script to process CLI arguments')
parser.add_argument('foo', type=str, help='a required argument')

args = parser.parse_args()

print(f"Argument provided: '{args.foo}'")

You can run this script like so:

python script.py foobar # "Argument provided: 'foobar'"

As you can see in the example above, argparse allows you to specify many more options than sys.argv. For example, the description and help options you specify can be seen when you pass the "-h" flag to the script:

python script.py -h

This will produce an output like the following:

a script to process CLI arguments

positional arguments:
  foo         a required argument

options:
  -h, --help  show this help message and exit

Please note that argparse offers built-in error handling; it provides a helpful error message when a required argument is missing.


This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.