Basic Python

argparse

Naranjito 2023. 12. 13. 12:43
  • argparse

When there is a Python script called run.py , we can run the file at the command prompt as follows.

$ ./run.py

 

If you want your Python script to work differently depending on the options, you'll need to get these arguments through the command line such as below.

$ ./run.py -d 1 -f

 

  • It must parse the arguments(ex, '-d', '-f') of the command line entered by the user,
  • and then perform appropriate actions according to the argument.
  • The module used to parse the arguments of the command line is argparse.

Add the arguments to parse via the add_argument method.

These are you should be aware of.

  • action="store" : to receive additional options.
  • action="store_true" : if you do not receive any additional options and just need the presence/absence of the options.
  • dest : Option values entered by the user are stored in the variable specified by the dest arguments.
  • required : Indicate whether an argument is required or optional, True or False.
  • help : Help message for an argument
  • default : Default value used when an argument is not provided, Defaults to None.

Example 1.

 

# run.py
import argparse

parser = argparse.ArgumentParser()
parser.add_argument("-d", "--decimal", dest="decimal", action="store") # extra value
parser.add_argument("-f", "--fast", dest="fast", action="store_true") # existence/nonexistence
args = parser.parse_args()

print(args.decimal)
print(args.fast)

 

parse_args() : Save the above(what added via add_argument) in args.


# terminal
$ ./run.py -d 1 -f

  • Parse the -d and -f options entered by the user 
  • and save 1 and True (because the -f option exists) to the args object 
  • and return.
# result
1          # args.decimal
True       # args.fast

 

 


Example 2.

 

parser = argparse.ArgumentParser()
parser.add_argument(dest="width", action="store")
parser.add_argument(dest="height", action="store")
parser.add_argument("--frames", dest="frames", action="store")
parser.add_argument("--qp", dest="qp", action="store")
parser.add_argument("--configure", dest="configure", action="store")

args = parser.parse_args(["64", "56", "--frames", "60", "--qp", "1", "--configure", "AI"])
print(args.width, args.height, args.frames, args.qp, args.configure)

 

https://wikidocs.net/73785

https://docs.python.org/3/library/argparse.html

'Basic Python' 카테고리의 다른 글

StringIO  (0) 2024.05.03
cv2.imread  (0) 2024.02.28
Logger, Handler, Filter, Formatter  (0) 2023.12.08
str VS repr  (0) 2023.11.16
getattr  (0) 2023.11.15