Leveraging argparse and sys.argv in 🐍Python for Command-Line Applications 🖥️

Edward Mike
2 min readMar 11, 2024

--

Are you still using input() function to gather user input in your Python scripts?. If you’re just starting out with Python programming, chances are you’ve relied on the input() function to gather user input

Let's talk about a more robust approach for handling command-line inputs: argparse and sys.argv.

👉 Why argparse and sys.argv?

  • argparse: A powerful module for parsing command-line arguments, offering flexibility and convenience in defining and parsing various types of inputs.
  • sys.argv: A simple and efficient way to access command-line arguments directly, without the need for manual parsing.

Here’s an example demonstrating how to use argparse to take a username and password as command-line arguments:

With this script, you can authenticate a user by providing a username and password as command-line arguments. Run this command in your terminal/shell in the same project directory. Assume my code resides in a file called myscript.py

python myscript.py — username admin — password admin123

Replace 'admin' and 'admin123' with the appropriate username and password combinations.

Lets look at another implementation using sys.argv to take a username and password as command-line arguments:

Run this command in your terminal/shell in the same project directory. Assume my code resides in a file called myscript.py

python myscript.py edward admin123

Replace 'edward' and 'admin123' with the appropriate username and password combinations

With both scripts, you can get a username and password by providing their username and password as a command-line argument, instead of using input() function.

🤢Example using input function.

input() function is suitable for simple interactions, it falls short in real-world applications where command-line inputs are more common and efficient.

🔧 Implementation:

  • argparse: Ideal for complex command-line interfaces with multiple arguments and options. While Python’s Typer and Click packages enhance its efficiency, simplifying console application development.
  • sys.argv: Suitable for simple scripts requiring minimal input handling and validation.

🌟 Best Practices:

  • Embrace argparse for projects with diverse input requirements and a focus on usability and scalability.
  • Utilize sys.argv for lightweight scripts with straightforward input handling, prioritizing simplicity and efficiency.

--

--