Python sys argv()

The sys.argv function in Python's sys module provides access to command-line arguments passed to a Python script. This function is useful for writing scripts that can accept user inputs or configurations directly from the command line.

Table of Contents

  1. Introduction
  2. sys.argv Function Syntax
  3. Examples
    • Basic Usage
    • Handling Multiple Arguments
    • Validating Command-Line Arguments
  4. Real-World Use Case
  5. Conclusion

Introduction

The sys.argv function in Python's sys module is a list in Python, which contains the command-line arguments passed to the script. With sys.argv, you can write flexible and interactive scripts that respond to user inputs provided at the time of execution.

sys.argv Function Syntax

Here is how you use sys.argv:

import sys

arguments = sys.argv

Parameters:

  • None. This function does not take any parameters.

Returns:

  • A list of strings representing the command-line arguments passed to the script.

Examples

Basic Usage

Here is an example of how to use sys.argv to access command-line arguments.

Example

import sys

# Accessing command-line arguments
print(f"Script name: {sys.argv[0]}")
if len(sys.argv) > 1:
    print(f"First argument: {sys.argv[1]}")
if len(sys.argv) > 2:
    print(f"Second argument: {sys.argv[2]}")

Running the script:

python script.py arg1 arg2

Output:

Script name: script.py
First argument: arg1
Second argument: arg2

Handling Multiple Arguments

This example demonstrates how to handle multiple command-line arguments using sys.argv.

Example

import sys

def main():
    if len(sys.argv) < 2:
        print("Usage: python script.py arg1 arg2 ... argN")
        sys.exit(1)

    for i, arg in enumerate(sys.argv):
        print(f"Argument {i}: {arg}")

if __name__ == "__main__":
    main()

Running the script:

python script.py arg1 arg2 arg3

Output:

Argument 0: script.py
Argument 1: arg1
Argument 2: arg2
Argument 3: arg3

Validating Command-Line Arguments

This example demonstrates how to validate the command-line arguments passed to a script.

Example

import sys

def main():
    if len(sys.argv) != 3:
        print("Usage: python script.py <input_file> <output_file>")
        sys.exit(1)

    input_file = sys.argv[1]
    output_file = sys.argv[2]

    # Validate file extensions
    if not input_file.endswith('.txt') or not output_file.endswith('.txt'):
        print("Error: Both input and output files must have .txt extension")
        sys.exit(1)

    print(f"Input file: {input_file}")
    print(f"Output file: {output_file}")

if __name__ == "__main__":
    main()

Running the script:

python script.py input.txt output.txt

Output:

Input file: input.txt
Output file: output.txt

Real-World Use Case

Processing Command-Line Arguments for a File Conversion Script

In real-world applications, sys.argv can be used to create flexible scripts that process files based on command-line arguments.

Example

import sys
import os

def convert_file(input_file, output_file):
    with open(input_file, 'r') as infile:
        content = infile.read()

    with open(output_file, 'w') as outfile:
        outfile.write(content.upper())

def main():
    if len(sys.argv) != 3:
        print("Usage: python script.py <input_file> <output_file>")
        sys.exit(1)

    input_file = sys.argv[1]
    output_file = sys.argv[2]

    if not os.path.exists(input_file):
        print(f"Error: Input file '{input_file}' does not exist")
        sys.exit(1)

    convert_file(input_file, output_file)
    print(f"File '{input_file}' has been converted to '{output_file}'")

if __name__ == "__main__":
    main()

Running the script:

python script.py input.txt output.txt

Output:

File 'input.txt' has been converted to 'output.txt'

Conclusion

The sys.argv function in Python's sys module provides access to command-line arguments passed to a script. This function is useful for writing flexible and interactive scripts that can accept user inputs or configurations directly from the command line. Proper usage of this function can enhance the usability and flexibility of your Python scripts by allowing them to respond to user-provided arguments.

Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare