I will be writing a number of Python scripts which will be run in batch daily on a Windows server. I am trying to develop a template for writing the scripts. My intention is to use a configuration file to hold the settings (for example: the location the log files will be saved in).
Below is the template I have developed so far and was wondering - can it be improved in some way? Thank you.
import datetime
from pathlib import Path
import configparser, argparse, logging
def main():
logging.info('Start Execution')
#
# Code goes here
#
logging.info('Execution Complete')
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument(
"-cf", "--config-file", type=str, required=True,
help="Path and filename to the config file.",
default=None
)
parser.add_argument(
"-ll", "--loglevel", type=str, required=False,
help="Defines the level of detail to be recorded in the log files; default is INFO.",
default='INFO'
)
argvs = parser.parse_args()
#Check a valid log level has been given
numeric_level = getattr(logging, argvs.loglevel.upper(), None)
if not isinstance(numeric_level, int):
raise ValueError(f"Invalid log level: {argvs.loglevel}")
# Check the config file exists
if not Path(argvs.config_file).is_file():
raise FileNotFoundError(f"Config File: {argvs.config_file}")
# Open and read-in the config file
# The Config File is open and read here as it makes the values available globally.
config = configparser.ConfigParser()
config.read(argvs.config_file)
#Configure logging
logging.basicConfig(
filename=config['SETTINGS']['log_path']+datetime.datetime.now().strftime("LOG_%G-%m-%d")+'.log'
,format='%(asctime)s - %(message)s'
,level=numeric_level
)
main()