From 9d83b7d736a6be220488879bb75cbdcda6afccba Mon Sep 17 00:00:00 2001 From: teutoburg Date: Mon, 23 Oct 2023 23:30:15 +0200 Subject: [PATCH] logging instead of print, pathlib instead of os --- skycalc_ipy/core.py | 38 ++++++++++++++++++++------------------ skycalc_ipy/ui.py | 32 ++++++++++++++++++-------------- 2 files changed, 38 insertions(+), 32 deletions(-) diff --git a/skycalc_ipy/core.py b/skycalc_ipy/core.py index 0cb7fa8..76800b4 100644 --- a/skycalc_ipy/core.py +++ b/skycalc_ipy/core.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- """ Based on the skycalc_cli package. @@ -5,11 +6,11 @@ Credit for ``skycalc_cli`` goes to ESO """ -from __future__ import print_function +import logging import hashlib import json -import os +from os import environ from datetime import datetime from pathlib import Path from typing import Dict @@ -21,10 +22,13 @@ try: import scopesim_data -except: +except ImportError: scopesim_data = None +CACHE_DIR = Path.home() / ".astar/skycalc_ipy" + + def get_cache_filenames(params: Dict, prefix: str, suffix: str): """Get filenames to cache the data. @@ -34,8 +38,8 @@ def get_cache_filenames(params: Dict, prefix: str, suffix: str): 3. The `data` directory in this package. """ - if "SKYCALC_IPY_CACHE_DIR" in os.environ: - dir_cache = Path(os.environ["SKYCALC_IPY_CACHE_DIR"]) + if "SKYCALC_IPY_CACHE_DIR" in environ: + dir_cache = Path(environ["SKYCALC_IPY_CACHE_DIR"]) elif isinstance(scopesim_data, ModuleType): dir_cache = scopesim_data.dir_cache_skycalc else: @@ -133,16 +137,18 @@ def __init__(self, indic): try: ra = float(indic["ra"]) - except ValueError: - print("Error: wrong ra format for the Almanac.") - raise + except ValueError as err: + logging.error("Wrong ra format for the Almanac.") + logging.exception(err) + raise err self.almindic["coord_ra"] = ra try: dec = float(indic["dec"]) - except ValueError: - print("Error: wrong dec format for the Almanac.") - raise + except ValueError as err: + logging.error("Wrong dec format for the Almanac.") + logging.exception(err) + raise err self.almindic["coord_dec"] = dec if "observatory" in indic: @@ -195,8 +201,8 @@ def query(self): try: almdata[key] = jsondata[subsection][value] except (KeyError, ValueError): - print(f"Warning: key \"{subsection}/{value}\" not found in the" - " Almanac response.") + logging.warning("Key '%s/%s' not found in Almanac response.", + subsection, value) return almdata @@ -403,9 +409,6 @@ def delete_server_tmpdir(self, tmpdir): ) def call(self, test=False): - # print 'self.url=',self.url - # print 'self.params=',self.params - if self.params["observatory"] in { "paranal", "lasilla", @@ -470,8 +473,7 @@ def callwith(self, newparams): if key in self.params: # valid self.params[key] = val else: - pass - # print('callwith() ignoring invalid keyword: ', key) + logging.debug("Ignoring invalid keyword: %s", key) self.call() def printparams(self, keys=None): diff --git a/skycalc_ipy/ui.py b/skycalc_ipy/ui.py index f205747..5da8701 100644 --- a/skycalc_ipy/ui.py +++ b/skycalc_ipy/ui.py @@ -1,5 +1,8 @@ -import os -import inspect +# -*- coding: utf-8 -*- +"""Skyclc IPY user interface.""" + +import logging +from pathlib import Path from datetime import datetime as dt import yaml @@ -25,8 +28,7 @@ class SkyCalc: def __init__(self, ipt_str=None): if ipt_str is None: - dirname = os.path.dirname(inspect.getfile(inspect.currentframe())) - ipt_str = os.path.join(dirname, "params.yaml") + ipt_str = Path(__file__).parent / "params.yaml" params = load_yaml(ipt_str) @@ -82,10 +84,11 @@ def validate_params(self): pass if invalid_keys: - print("See .comments[] for help") - print("The following entries are invalid:") + logging.warning("See .comments[] for help") + logging.warning("The following entries are invalid:") for key in invalid_keys: - print(f"'{key}' : {self.values[key]} : {self.comments[key]}") + logging.warning("'%s' : %s : %s", key, + self.values[key], self.comments[key]) return not invalid_keys @@ -208,8 +211,8 @@ def get_sky_spectrum(self, return_type="table", filename=None): points=tbl["lam"].data * tbl["lam"].unit, lookup_table=tbl["flux"].data * funit, ) - print( - "Warning: synphot doesn't accept surface brightnesses \n" + logging.warning( + "Synphot doesn't accept surface brightnesses \n" "The resulting spectrum should be multiplied by arcsec-2" ) @@ -241,11 +244,12 @@ def keys(self): def load_yaml(ipt_str): - if ".yaml" in ipt_str.lower(): - if not os.path.exists(ipt_str): - raise ValueError(ipt_str + " not found") + # TODO: why not just load, what's all of this? + if ".yaml" in str(ipt_str).lower(): + if not ipt_str.exists(): + raise ValueError(f"{ipt_str} not found") - with open(ipt_str, "r") as fd: + with ipt_str.open("r", encoding="utf-8") as fd: fd = "\n".join(fd.readlines()) opts_dict = yaml.load(fd, Loader=yaml.FullLoader) else: @@ -263,7 +267,7 @@ def get_almanac_data( observatory=None, ): if date is not None and mjd is not None: - print("Warning: Both date and mjd are set. Using date") + logging.warning("Both date and mjd are set. Using date") skycalc_params = SkyCalc() skycalc_params.values.update({"ra": ra, "dec": dec, "date": date, "mjd": mjd})