Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

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 :: python extraer ultimo elemento lista 
Python :: how to sort subset of rows in pandas df 
Python :: Dictionary get both key and value. 
Python :: how to interrupt a loop in python 
Python :: python chunk text 
Python :: find email address pytho 
Python :: pandas csv sum column 
Python :: includes python 
Python :: copy along additional dimension numpy 
Python :: input and print 
Python :: python logging levels 
Python :: python 3.7 download 
Python :: pandas cumsum 
Python :: how to scan directory recursively python 
Python :: scipy.stats.spearmanr 
Python :: explode multiple columns pandas 
Python :: Python get the name of the song that is playing 
Python :: 151 - Power Crisis solution in python 
Python :: Reducing noise on Data 
Python :: bad request 400 heroku app 
Python :: set difference in multidimensional array numpy 
Python :: python popen 
Python :: statsmodels fitted values 
Python :: how to extract column from numpy array 
Python :: store command in discord.py 
Python :: insert a new row to numpy array in especific position 
Python :: case python 
Python :: install tabula 
Python :: how to take first half of list python 
Python :: python replace text 
ADD CONTENT
Topic
Content
Source link
Name
2+8 =