Exception message argparse to be redirect to logger : Python

Viewed 10
import argparse
import logging
handlers = [logging.FileHandler('logger.log',mode='a'), logging.StreamHandler() ] 
logging.basicConfig( level=logging.DEBUG,format='[%(levelname)s] %(message)s' ,handlers = handlers )    
    
parser = argparse.ArgumentParser();
parser = argparse.ArgumentParser(description="./script.py --db <db path>  --scratch <scratch path> ")
required_args = parser.add_argument_group('required arguments')
required_args.add_argument('--db' , '-d', type=str, help='db directory name. Default is release',required=True)
  
required_args.add_argument('--scratch', '-s', type=str, help='Scratch path where report will be written')

try:
   args = parser.parse_args()
except  SystemExit as se:
   logging.fatal("Invalid Command line argument:" )

Hello, I have a code block like the above. I wanted to redirect messages that agrparse throws in case of invalid arguments into the logging. Also, I wanted to capture this as a part of the exception. But argparse seems throws errors on stdout only. Is there any easy way to do it?

Regards, Debabrata

0 Answers
Related