Python: How to read command line arguments

In Python, you can read the first command-line argument passed to a script using the sys.argv list from the sys module. The first element…

Python: How to read command line arguments
Photo by Hitesh Choudhary on Unsplash

In Python, you can read the first command-line argument passed to a script using the sys.argv list from the sys module. The first element of this list (sys.argv[0]) is the name of the script itself, and subsequent elements (sys.argv[1], sys.argv[2], etc.) are the command-line arguments.

Here’s an example of how to read the first command-line argument:

import sys 
 
if len(sys.argv) > 1: 
    # The first command-line argument is at sys.argv[1] 
    first_argument = sys.argv[1] 
    print(f"The first command-line argument is: {first_argument}") 
else: 
    print("No command-line arguments provided.")

In this example, we first check if there are any command-line arguments (the length of sys.argv is greater than 1). If there is at least one argument, we access the first one using sys.argv[1] and print it. If no arguments are provided, we print a message indicating that.

To run this script, save it as a .py file and run it from the command line with an argument:

python script.py argument1

Replace script.py with your script's filename and argument1 with the actual command-line argument you want to read.

The argparse module

Using the argparse module is a more structured and user-friendly way to handle command-line arguments in Python. It allows you to define expected command-line arguments, their types, descriptions, and default values. Here's an example of how to use argparse to read the first command-line argument:

import argparse 
 
def main(): 
    # Create an ArgumentParser object 
    parser = argparse.ArgumentParser(description="Read the first command-line argument") 
 
    # Define a positional argument for the first command-line argument 
    parser.add_argument('arg1', type=str, help="The first command-line argument") 
 
    # Parse the command-line arguments 
    args = parser.parse_args() 
 
    # Access and print the first argument 
    first_argument = args.arg1 
    print(f"The first command-line argument is: {first_argument}") 
 
if __name__ == "__main__": 
    main()

In this script:

  1. We import the argparse module.
  2. We define a function main where we set up the argument parser and handle the command-line arguments.
  3. We create an ArgumentParser object called parser with a description.
  4. We define a positional argument arg1 using parser.add_argument(). The type parameter specifies the expected data type of the argument, and help provides a description.
  5. We parse the command-line arguments using parser.parse_args(), which returns an args object containing the parsed arguments.
  6. We access the first argument using args.arg1 and print it.
  7. Finally, we call the main() function if the script is run directly.

To run this script, save it as a .py file and run it from the command line:

python script.py argument1

Replace script.py with your script's filename and argument1 with the actual command-line argument you want to read. The script will also provide a helpful message if you run it without any arguments or with the -h or --help option to display the usage information.

Conclusion

In this discussion, we explored two different methods for reading and validating command-line arguments in Python:

  1. Reading Command-Line Arguments with sys.argv:
  • sys.argv is a simple way to access command-line arguments.
  • You can access the first argument using sys.argv[1], but it requires manual parsing and validation.
  • It’s suitable for basic scripts with a limited number of arguments.

2. Reading Command-Line Arguments with argparse:

  • argparse is a more robust and user-friendly way to handle command-line arguments.
  • It provides a structured way to define and validate arguments, including data types, descriptions, and default values.
  • Ideal for complex scripts or applications that require proper argument handling and validation.

Here’s a summary of when to use each method:

  • Use sys.argv when you have a simple script with a small number of command-line arguments, and you don't need advanced validation or argument descriptions.
  • Use argparse when you need to define, document, and validate command-line arguments systematically, especially for complex scripts or applications.

The choice between these methods depends on the complexity of your script and your specific requirements for handling and validating command-line arguments.

Join Medium with my referral link - Konstantinos Patronas
As a Medium member, a portion of your membership fee goes to writers you read, and you get full access to every story…