How to Make Python Argparse Read in a Folder of Files

Command-Line Option and Statement Parsing using argparse in Python

Command line arguments are those values that are passed during the calling of the programme along with the calling statement. Usually, python uses sys.argv array to bargain with such arguments merely hither we describe how it tin can exist made more than resourceful and user-friendly by employing argparse module.

Argparse Module

The argparse module in Python helps create a plan in a command-line-environs in a way that appears not only easy to code only besides improves interaction. The argparse module also automatically generates help and usage messages and issues errors when users give the programme invalid arguments.

Steps for Using Argparse

  1. Creating a Parser: Importing argparse module is the first style of dealing with the concept. Afterwards you lot've imported it you have to create a parser or an ArgumentParser object that will shop all the necessary information that has to be passed from the python command-line.

    Syntax: class argparse.ArgumentParser(prog=None, usage=None, description=None, epilog=None, parents=[], formatter_class=argparse.HelpFormatter, prefix_chars='-', fromfile_prefix_chars=None, argument_default=None, conflict_handler='error', add_help=Truthful, allow_abbrev=True)

    Parameters:

    • prog– name of the programme (default=sys.argv[0])
    • usage– string describes the program usage(default: generated from arguments added to the parser)
    • clarification– text to display earlier the argument assist(default: none)
    • epilog– text to brandish afterward the statement aid (default: none)
    • parents– list of ArgumentParser objects whose arguments should too be included
    • formatter_class– class for customizing the help output
    • prefix_chars– set up of characters that prefix optional arguments (default: '-')
    • fromfile_prefix_chars– gear up of characters that prefix files from which additional arguments should exist read (default: None)
    • argument_default– global default value for arguments (default: None)
    • conflict_handler– strategy for resolving conflicting optionals (usually unnecessary)
    • add_help– Add a -h/–help option to the parser (default: Truthful)
    • allow_abbrev– Allows long options to exist abbreviated if the abbreviation is unambiguous. (default: Truthful)
  2. Adding Arguments: Adjacent step is to fill the ArgumentParser with the information about the arguments of the program. This implies a call to the add_argument() method. These information tell ArgumentParser how to take arguments from the command-line and turn them into objects.

    Syntax: ArgumentParser.add_argument(proper noun or flags…[, activity][, nargs][, const][, default][, type][, choices][, required][, assist][, metavar][, dest])

    Parameters:

    • name or flags– either a name or list of selection string
    • activity– basic type of action to be taken when this statement is encountered at the command line
    • nargs– number of control-line arguments that should exist consumed
    • const– abiding value required by some activeness and nargs selections
    • default– value produced if the arguments are absent-minded from the command line
    • type– type to which the control line arguments should be converted.
    • choices – A container of the allowable values for the argument
    • required – Whether or not the command-line option may be omitted (optionals only)
    • assist– brief clarification of what the argument does
    • metavar – A proper noun for the statement in usage messages
    • dest – The name of the aspect to be added to the object returned past parse_args()
  3. Parsing Arguments: The data gathered in the footstep 2 is stored and used when arguments are parsed through parse_args(). The data is initially stored in sys.argv array in a string format. Calling parse_args() with the control-line data first converts them into the required data type then invokes the appropriate activity to produce a event.

    Syntax: ArgumentParser.parse_args(args=None, namespace=None)

    Parameter:

    • args – List of strings to parse. The default is taken from sys.argv.
    • namespace – An object to take the attributes. The default is a new empty Namespace object

    In most cases, this ways a unproblematic Namespace object volition be built up from attributes parsed out of the command line:

    Namespace(accumulate=, integers=[ 2, 8, -vii, 41 ])

These were the root concepts you need to be familiar with to deal with argparse. The following are some examples to support this awarding.

Example 1: To notice the sum of command-line arguments using argparse

import argparse

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

parser.add_argument( 'integers' , metavar = 'N' ,

type = int , nargs = '+' ,

assist = 'an integer for the accumulator' )

parser.add_argument(dest = 'accrue' ,

action = 'store_const' ,

const = sum ,

aid = 'sum the integers' )

args = parser.parse_args()

impress (args.accumulate(args.integers))

Output:

python-argparse

Example 2: Program to arrange the integer inputs in ascending gild

import argparse

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

parser.add_argument( 'integers' ,

metavar = 'N' ,

type = int ,

nargs = '+' ,

help = 'an integer for the accumulator' )

parser.add_argument(dest = 'accumulate' ,

action = 'store_const' ,

const = sorted ,

help = 'arranges the integers in ascending order' )

args = parser.parse_args()

impress (args.accumulate(args.integers))

Output:
python-argparse

Example 3: To find the average of the entered command line numerical arguments

import argparse

parser = argparse.ArgumentParser(clarification = 'sort some integers.' )

parser.add_argument( 'integers' ,

metavar = 'N' ,

type = bladder ,

nargs = '+' ,

help = 'an integer for the accumulator' )

parser.add_argument( 'sum' ,

activeness = 'store_const' ,

const = sum )

parser.add_argument( 'len' ,

action = 'store_const' ,

const = len )

args = parser.parse_args()

add = args. sum (args.integers)

length = args. len (args.integers)

average = add together / length

print (average)

Output:
python-argparse

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the nuts.

To begin with, your interview preparations Raise your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, bring together the Machine Learning - Bones Level Course


brentlichannoosee.blogspot.com

Source: https://www.geeksforgeeks.org/command-line-option-and-argument-parsing-using-argparse-in-python/

0 Response to "How to Make Python Argparse Read in a Folder of Files"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel