Python provides several ways to read user input and command line arguments, making it a versatile language for interactive programs and scripts. In this tutorial, we will explore how to use built-in functions and modules to accept user input and parse command line arguments.
Reading User Input
To read user input in Python, you can use the input()
function (or raw_input()
in Python 2.x). This function prompts the user with a message and returns the input as a string. Here’s an example:
user_input = input("Please enter something: ")
print("You entered:", user_input)
Note that in Python 2.x, input()
tries to evaluate the input as a Python expression, which can be a security risk if you’re not careful. That’s why raw_input()
is recommended for reading user input in Python 2.x.
Reading Command Line Arguments
Command line arguments are passed to your Python script when it’s executed from the command line. You can access these arguments using the sys.argv
list, where sys
is a built-in module. Here’s an example:
import sys
print("Command line arguments:", sys.argv)
When you run this script from the command line with arguments, sys.argv
will contain a list of strings representing each argument.
Parsing Command Line Arguments
While sys.argv
is useful for simple cases, it’s often better to use a dedicated module like argparse
to parse command line arguments. argparse
provides a powerful and flexible way to define and parse arguments. Here’s an example:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("name", help="your name")
args = parser.parse_args()
print("Hello, {}!".format(args.name))
In this example, we define an ArgumentParser
instance and add a single argument called name
. When the script is run with a command line argument, argparse
will parse it and store it in the args
object.
Using argparse to Parse Complex Arguments
argparse
can handle more complex cases, such as optional arguments, flags, and sub-commands. Here’s an example:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("square", help="display a square of a given number", type=int)
args = parser.parse_args()
print(args.square ** 2)
In this example, we define an ArgumentParser
instance and add a single argument called square
, which is expected to be an integer. If the user passes a non-integer value, argparse
will raise an error.
Best Practices
When reading user input and command line arguments in Python, keep the following best practices in mind:
- Always validate and sanitize user input to prevent security vulnerabilities.
- Use
input()
(orraw_input()
in Python 2.x) for reading user input, rather thansys.stdin
. - Use
argparse
or another dedicated module for parsing command line arguments, rather than relying onsys.argv
.
By following these guidelines and using the built-in functions and modules provided by Python, you can write robust and interactive programs that handle user input and command line arguments with ease.