Skip to content

Commit

Permalink
logging instead of print, pathlib instead of os
Browse files Browse the repository at this point in the history
  • Loading branch information
teutoburg committed Oct 23, 2023
1 parent 85f0faf commit 9d83b7d
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 32 deletions.
38 changes: 20 additions & 18 deletions skycalc_ipy/core.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
# -*- coding: utf-8 -*-
"""
Based on the skycalc_cli package.
This modele was taken (mostly unmodified) from ``skycalc_cli`` version 1.1.
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
Expand All @@ -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.
Expand All @@ -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:
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -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):
Expand Down
32 changes: 18 additions & 14 deletions skycalc_ipy/ui.py
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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)

Expand Down Expand Up @@ -82,10 +84,11 @@ def validate_params(self):
pass

if invalid_keys:
print("See <SkyCalc>.comments[<key>] for help")
print("The following entries are invalid:")
logging.warning("See <SkyCalc>.comments[<key>] 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

Expand Down Expand Up @@ -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"
)

Expand Down Expand Up @@ -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:
Expand All @@ -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})
Expand Down

0 comments on commit 9d83b7d

Please sign in to comment.