Python Script: Accept Console Input & CLI Arguments

How can I create a Python script that accepts python console input and also reads in arguments when run from the command line?

Sure, here’s a straightforward approach I often use when working with interactive user input. The built-in input() function is perfect for this. It lets you capture user input directly during the execution of the script.

# Accepting user input using python console input
user_input = input("Please enter your name: ")
print(f"Hello, {user_input}!")

This will prompt the user to enter their name, and the script will print a greeting. It’s simple, intuitive, and perfect for handling python console input during runtime when interactivity is needed

That’s a great start, Sam! But if you’re running the script from the command line and want to provide arguments directly, you can use sys.argv. It’s great for quick setups when you’re passing simple arguments from the terminal.

import sys

# Reading arguments from the command line (python console input)
if len(sys.argv) > 1:
    print(f"Hello, {sys.argv[1]}!")
else:
    print("Hello, World!")

For instance, if you save this script as script.py, you can pass the name like this:

python script.py John

This way, you have another way to handle python console input efficiently, especially for command-line scenarios.

Both approaches work wonderfully! But if you’re dealing with more complex scenarios where you need to validate inputs or handle multiple arguments, I’d recommend using argparse. It’s a robust module that provides a lot of control over argument parsing.

import argparse

# Set up the argument parser
parser = argparse.ArgumentParser(description="Example of python console input handling")
parser.add_argument("name", help="Enter your name")
# Parse the arguments
args = parser.parse_args()

print(f"Hello, {args.name}!")

With this, you can run the script like so:

python script.py John

The argparse module is highly flexible and makes handling python console input seamless, especially for more advanced use cases where validation and optional arguments come into play.