From 11a5809f6a0e8129ffa762137dcf50168548b10c Mon Sep 17 00:00:00 2001 From: djib Date: Tue, 19 May 2020 00:06:33 +0200 Subject: [PATCH] Improve error handling with config file --- .gitignore | 2 +- PDMameUpdate.py | 45 +++++++++++++++++++++++++++++++++++---------- 2 files changed, 36 insertions(+), 11 deletions(-) diff --git a/.gitignore b/.gitignore index 59855f4..3cb27c4 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,3 @@ -config.json .project .pydevproject +PDMameUpdate.json diff --git a/PDMameUpdate.py b/PDMameUpdate.py index 068a988..8cbb4cb 100755 --- a/PDMameUpdate.py +++ b/PDMameUpdate.py @@ -33,12 +33,12 @@ Notes a cookies.txt file in the .config/transmission directory See: https://forum.transmissionbt.com/viewtopic.php?t=7468 -/!\/!\/!\/!\/!\/!\/!\/!\/!\/!\/!\/!\/!\/!\/!\/!\ -/!\ Provided with no warranty whatsoever. /!\ -/!\ Make sure you understand what the script /!\ -/!\ does and adapt it to your context /!\ -/!\ Use with caution. /!\ -/!\/!\/!\/!\/!\/!\/!\/!\/!\/!\/!\/!\/!\/!\/!\/!\ +!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! +!!! Provided with no warranty whatsoever. !!! +!!! Make sure you understand what the script !!! +!!! does and adapt it to your context !!! +!!! Use with caution. !!! +!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ''' import argparse import feedparser @@ -59,17 +59,41 @@ from urllib.parse import quote def open_config_file(): """Reads configuration from PDMameUpdate.json file""" - for loc in os.environ.get("PDMAMEUPDATE_CONF"), "/etc", os.path.expanduser("~"), os.curdir: + locations = ( + os.environ.get("PDMAMEUPDATE_CONF"), + "/etc", + os.path.expanduser("~"), + os.curdir + ) + for loc in locations: if loc is not None: + logging.info("Searching for config file in '%s'", loc) config_path = loc + '/PDMameUpdate.json' if pathlib.Path(config_path).is_file(): - config_file_loc = config_path - break + config_file_loc = config_path + break + + if 'config_file_loc' not in locals(): + logging.error("Config file not found") + raise FileNotFoundError("Config file not found") logging.info('Opening config file: '+config_file_loc) - config_file = None; + config_file = None with open(config_file_loc, 'r') as config_file: config = json.load(config_file) + parameters = [ + "mame-directory", + "pleasuredome-password", + "pleasuredome-user", + "torrent-directory", + "transmission-password", + "transmission-port", + "transmission-user" + ] + for key in parameters: + if key not in config: + logging.error('Missing key in config file: %s', key) + raise ValueError('Invalid config file.') return config @@ -251,6 +275,7 @@ def update_torrents(): t = requests.get(torrent['remote-link'], verify=False) open(new_torrent, 'wb').write(t.content) + if __name__ == '__main__': logging.basicConfig( level=logging.WARNING,