Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

how to use argparse

import argparse

if __name__ == "__main__":
	#add a description
	parser = argparse.ArgumentParser(description="what the program does")

	#add the arguments
	parser.add_argument("arg1", help="advice on arg")
	parser.add_argument("arg2", help="advice on arg")
#						.
# 						.
#   					.
	parser.add_argument("argn", help="advice on arg")

	#this allows you to access the arguments via the object args
	args = parser.parse_args()

	#how to use the arguments
	args.arg1, args.arg2 ... args.argn
Comment

argparse cli

# importing required modules
import argparse
 
# create a parser object
parser = argparse.ArgumentParser(description = "An addition program")
 
# add argument
parser.add_argument("add", nargs = '*', metavar = "num", type = int,
                     help = "All the numbers separated by spaces will be added.")
 
# parse the arguments from standard input
args = parser.parse_args()
 
# check if add argument has any input data.
# If it has, then print sum of the given numbers
if len(args.add) != 0:
    print(sum(args.add))
Comment

argparse for Command-Line Interface (CLI)

import argparse
import sys

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--x', type=float, default=1.0,
                        help='What is the first number?')
    parser.add_argument('--y', type=float, default=1.0,
                        help='What is the second number?')
    parser.add_argument('--operation', type=str, default='add',
                        help='What operation? Can choose add, sub, mul, or div')
    args = parser.parse_args()
    sys.stdout.write(str(calc(args)))
    
def calc(args):
    if args.operation == 'add':
        return args.x + args.y
    elif args.operation == 'sub':
        return args.x - args.y
    elif args.operation == 'mul':
        return args.x * args.y
    elif args.operation == 'div':
        return args.x / args.y

if __name__ == '__main__':
    main()
Comment

PREVIOUS NEXT
Code Example
::  
:: python os get path 
::  
Python :: Write a program that prints #pythoniscool, followed by a new line, in the standard output. Your program should be maximum 2 lines long You are not allowed to use print or eval or open or import sys in your file 
Python :: python iterating through a string 
Python ::  
:: python venv flask 
Python ::  
::  
Python ::  
Python ::  
Python :: python print without new lines 
Python :: get request body flask 
Python :: django authenticate 
Python :: python numpy matrix to list 
Python :: how to save dataframe as csv in python 
Python :: looping through nested dictionary to nth 
Python ::  
::  
Python ::  
:: zip multiple lists 
Python ::  
::  
Python ::  
Python ::  
:: python square a number 
Python :: Visualize Decision Tree 
Python :: list to dict python with same values 
Python :: python hasattribute 
Python ::  
ADD CONTENT
Topic
Content
Source link
Name
8+3 =