How do you handle command-line arguments in Python?

Learn how to process user input from the command line using Python’s argparse module. This is a crucial skill for building flexible and powerful scripts. …

Updated August 26, 2023



Learn how to process user input from the command line using Python’s argparse module. This is a crucial skill for building flexible and powerful scripts.

Command-line arguments allow users to interact with your Python programs by providing extra information directly when they run the script. Imagine you have a program that converts temperatures. Instead of hardcoding the temperature unit, command-line arguments let the user choose between Celsius or Fahrenheit.

Why are command-line arguments important?

They make your programs:

  • Flexible: Users can customize how your program runs without needing to change the code itself.
  • Reusable: A single script can handle different tasks depending on the provided arguments.
  • Powerful: They enable complex interactions and data processing directly from the command line.

This question is frequently asked in Python interviews because it demonstrates:

  1. Understanding of core Python modules: You need to know how argparse (or other argument parsing libraries) work.
  2. Ability to write modular code: Handling arguments effectively promotes clean and reusable code structure.

Let’s dive into a practical example using the argparse module:

import argparse

def main():
  # Create an ArgumentParser object
  parser = argparse.ArgumentParser(description='Convert temperatures.') 

  # Add arguments:
  parser.add_argument('temperature', type=float, help='Temperature value to convert')
  parser.add_argument('-u', '--unit', choices=['C', 'F'], default='C', 
                      help='Unit of the input temperature (C or F)')

  # Parse the arguments
  args = parser.parse_args()

  # Perform conversion based on arguments
  if args.unit == 'C':
    converted_temp = (args.temperature * 9/5) + 32
    print(f"{args.temperature}°C is equal to {converted_temp:.2f}°F")
  else: # args.unit == 'F'
    converted_temp = (args.temperature - 32) * 5/9
    print(f"{args.temperature}°F is equal to {converted_temp:.2f}°C")

if __name__ == "__main__":
  main()

Step-by-Step Explanation:

  1. Import argparse: This line brings in the necessary tools for handling command-line arguments.

  2. Create a parser:

    parser = argparse.ArgumentParser(description='Convert temperatures.') 
    

    This creates an ArgumentParser object, which will help us define and process the arguments. The description string appears when users request help (e.g., by typing python your_script.py -h).

  3. Add arguments:

    parser.add_argument('temperature', type=float, help='Temperature value to convert')
    parser.add_argument('-u', '--unit', choices=['C', 'F'], default='C', 
                        help='Unit of the input temperature (C or F)')
    
    • We use add_argument to define each argument:
      • ’temperature’: This is a positional argument, meaning it must be provided directly after the script name. It expects a floating-point number and has a helpful description.
      • ’-u’, ‘–unit’: This is an optional argument. Users can specify it with either -u or --unit.
        • choices=['C', 'F'] restricts the allowed values.
        • default='C' sets Celsius as the default if no unit is provided.
  4. Parse arguments:

    args = parser.parse_args()
    

    This line processes the command-line input and stores the parsed arguments in an object called args. You can access each argument’s value using dot notation (e.g., args.temperature, args.unit).

  5. Use the arguments: The code then uses the values stored in args to perform the temperature conversion based on the user’s input unit.

Running the Script:

python your_script.py 25 -u C  # Converts 25°C to °F
python your_script.py 77 -u F  # Converts 77°F to °C
python your_script.py 30       # Defaults to converting 30°C to °F

Try modifying this code to handle different types of arguments, add more complex logic, or explore other argument parsing libraries available in Python!


Stay up to date on the latest in Computer Vision and AI

Intuit Mailchimp