StudyLover
  • Home
  • Study Zone
  • Profiles
  • Contact us
  • Sign in
StudyLover CLI Args
Download
  1. Python
  2. OOP: A Comprehensive Guide
Iterators : Most frequent words in a text read from a file
OOP: A Comprehensive Guide

Command-Line Arguments

Command-line arguments allow you to pass information to a Python script when you execute it from the command line. This provides flexibility and makes your scripts more interactive.

Methods to Handle Command-Line Arguments:

1.    Using sys.argv:

o    The sys.argv list contains all the command-line arguments passed to the script.

o    sys.argv[0] is the script name itself.

o    Subsequent indices access the arguments.

Python

import sys

 

if len(sys.argv) < 2:

    print("Usage: python script.py <argument1> <argument2>")

    sys.exit(1)

 

argument1 = sys.argv[1]

argument2 = sys.argv[2]

 

print("Argument 1:", argument1)

print("Argument 2:", argument2)

2.    Using the getopt Module:

o    The getopt module provides a more structured way to handle options and arguments.

o    You can define short options (like -h for help) and long options (like --help).

Python

import getopt

 

def main(argv):

    try:

        opts, args = getopt.getopt(argv, "hi:o:", ["help", "input=", "output="])

    except getopt.GetoptError:

        print('script.py -i <inputfile> -o <outputfile>')

        sys.exit(2)

 

    for opt, arg in opts:

        if opt in ("-h", "--help"):

            print('script.py -i <inputfile> -o <outputfile>')

            sys.exit()

        elif opt in ("-i", "--input"):

            inputfile = arg

        elif opt in ("-o", "--output"):

            outputfile = arg

 

if __name__ == "__main__":

    main(sys.argv[1:])

3.    Using the argparse Module:

o    The argparse module is the recommended way to parse command-line arguments.

o    It provides a more user-friendly and flexible interface.

Python

import argparse

 

parser = argparse.ArgumentParser(description='Process some integers.')

parser.add_argument('integers', metavar='N', type=int, nargs='+',

                    help='an integer for the accumulator')

parser.add_argument('--sum', dest='accumulate', action='store_const',

                    const=sum, default=max,

                    help='sum the integers (default: find the max)')

 

args = parser.parse_args()

 

print(args.accumulate(args.integers))  

 

Key Points:

  • Error Handling: Always check the number of arguments to avoid IndexError.

  • Type Conversion: If necessary, convert command-line arguments to appropriate data types (e.g., integers, floats, or booleans).

  • User-Friendly Input: The argparse module provides features like help messages, default values, and type checking.

  • Flexibility: Choose the method that best suits your specific needs and complexity.

By effectively using command-line arguments, you can create more powerful and customizable Python scripts.

 

Python

import sys

 

def word_count(filename):

    """Counts the words in a text file.

 

    Args:

        filename: The name of the file to process.

 

    Returns:

        The number of words in the file.

    """

 

    try:

        with open(filename, 'r') as file:

            word_count = len(file.read().split())

            return word_count

    except FileNotFoundError:

        print(f"Error: File '{filename}' not found.")

        return 0

 

if __name__ == "__main__":

    if len(sys.argv) != 2:

        print("Usage: python word_count.py <filename>")

    else:

        filename = sys.argv[1]

        word_count = word_count(filename)

        print(f"The file '{filename}' contains {word_count} words.")

 

Iterators Most frequent words in a text read from a file
Our Products & Services
  • Home
Connect with us
  • Contact us
  • +91 82955 87844
  • Rk6yadav@gmail.com

StudyLover - About us

The Best knowledge for Best people.

Copyright © StudyLover
Powered by Odoo - Create a free website