Jul-04-2020, 12:44 AM
Hello Guys, quick question from a beginner. I am learning about the module argparse and I wanted to know about this code. You see the positional arguments there -a and -b , these are storing values right. Suppose, I type on the terminal -a 42 -b 36, is there are way to extract those variables from the terminal to my program so that I can use those numbers for some functions. For e.g I might want to use the numbers entered 42 and 36 to be used in a function called sum where I add these two numbers. Basically, how do I capture their values entered because a, b are not actual variables that I can use.
import argparse import os import sys if __name__=="__main__": # Create the parser my_parser = argparse.ArgumentParser(prog='parsing', description='List the content of a folder', epilog='Enjoy the program :)') # Add the arguments my_parser.add_argument('Path', metavar='path', type=str, help='the path to list') my_parser.add_argument('-a', action='store', help='This is 1st arg') my_parser.add_argument('-b', action='store', help='This is 2nd arg') my_parser.add_argument('-l', '--long', action='store_true', help='enable the long listing format') # Execute the parse_args() method args = my_parser.parse_args() print("All parameters have been read") input_path = args.Path if not os.path.isdir(input_path): print('The path specified does not exist') sys.exit() for line in os.listdir(input_path): if args.long: #simplified long listing size = os.stat(os.path.join(input_path, line)).st_size line = '%10d %s' % (size, line) print(line)