Skip to content

Commit bc67fe8

Browse files
authored
Merge pull request #1096 from xylar/fix-pkg-resources
Switch from `pkg_resources` to `importlib.resources`
2 parents 909e6c9 + 49635b4 commit bc67fe8

File tree

4 files changed

+50
-68
lines changed

4 files changed

+50
-68
lines changed

mpas_analysis/download_data.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@
1919

2020

2121
import argparse
22-
import pkg_resources
22+
import importlib.resources as resources
2323
import os
2424

2525
from mpas_analysis.shared.io.download import download_files
@@ -49,9 +49,10 @@ def download_analysis_data():
4949
pass
5050

5151
urlBase = 'https://web.lcrc.anl.gov/public/e3sm/diagnostics'
52-
analysisFileList = pkg_resources.resource_string(
53-
'mpas_analysis',
54-
'obs/{}_input_files'.format(args.dataset)).decode('utf-8')
52+
resource = resources.files('mpas_analysis.obs').joinpath(
53+
f'{args.dataset}_input_files')
54+
with resource.open('r') as f:
55+
analysisFileList = f.read()
5556

5657
# remove any empty strings from the list
5758
analysisFileList = list(filter(None, analysisFileList.split('\n')))

mpas_analysis/ocean/climatology_map_custom.py

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -23,12 +23,14 @@
2323

2424
class ClimatologyMapCustom(AnalysisTask):
2525
"""
26-
A felxible analysis task for plotting climatologies of any MPAS-Ocean field
26+
A flexible analysis task for plotting climatologies of any MPAS-Ocean field
2727
on cells from timeSeriesStatsMonthly at various depths (if the field has
28-
vertical levels) and for various seasons. Various derived fields are also
29-
supported:
30-
* velocity magnitude
31-
* thermal forcing (temperature - freezing temperature)
28+
vertical levels) and for various seasons.
29+
30+
Various derived fields are also supported:
31+
32+
* velocity magnitude
33+
* thermal forcing (temperature - freezing temperature)
3234
"""
3335

3436
def __init__(self, config, mpasClimatologyTask, controlConfig=None):

mpas_analysis/shared/html/pages.py

Lines changed: 38 additions & 59 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616
from os import makedirs
1717
from pathlib import Path
1818

19-
import pkg_resources
19+
import importlib.resources as resources
2020
from lxml import etree
2121

2222
import mpas_analysis.version
@@ -66,13 +66,13 @@ def generate_html(config, analyses, controlConfig, customConfigFiles):
6666
try:
6767
ComponentPage.add_image(fileName, config, components,
6868
controlConfig)
69-
except IOError:
70-
print(' missing file {}'.format(fileName))
69+
except IOError as e:
70+
print(f'Error reading {fileName}: {e}')
7171
missingCount += 1
7272

7373
if missingCount > 0:
74-
print('Warning: {} XML files were missing and the analysis website'
75-
' will be incomplete.'.format(missingCount))
74+
print(f'Warning: {missingCount} XML files could not be read and the '
75+
f'analysis website will be incomplete.')
7676
# generate the page for each component and add the component to the main
7777
# page
7878
for componentName, component in components.items():
@@ -155,24 +155,15 @@ def __init__(self, config, controlConfig, customConfigFiles):
155155
self.customConfigFiles = customConfigFiles
156156

157157
# get template text
158-
fileName = \
159-
pkg_resources.resource_filename(__name__,
160-
"templates/main_page.html")
161-
162-
with open(fileName, 'r') as templateFile:
163-
self.pageTemplate = templateFile.read()
164-
165-
fileName = \
166-
pkg_resources.resource_filename(__name__,
167-
"templates/main_component.html")
168-
with open(fileName, 'r') as templateFile:
169-
self.componentTemplate = templateFile.read()
170-
171-
fileName = \
172-
pkg_resources.resource_filename(__name__,
173-
"templates/config.html")
174-
with open(fileName, 'r') as templateFile:
175-
self.configTemplate = templateFile.read()
158+
package = 'mpas_analysis.shared.html.templates'
159+
templates = {}
160+
for name in ['main_page', 'main_component', 'config']:
161+
resource = resources.files(package).joinpath(f'{name}.html')
162+
with resource.open('r') as templateFile:
163+
templates[name] = templateFile.read()
164+
self.pageTemplate = templates['main_page']
165+
self.componentTemplate = templates['main_component']
166+
self.configTemplate = templates['config']
176167

177168
# start with no components
178169
self.components = OrderedDict()
@@ -273,45 +264,34 @@ def generate(self):
273264

274265
pageText = _replace_tempate_text(self.pageTemplate, replacements)
275266

276-
htmlBaseDirectory = build_config_full_path(self.config, 'output',
277-
'htmlSubdirectory')
267+
htmlBaseDirectory = build_config_full_path(
268+
self.config, 'output', 'htmlSubdirectory'
269+
)
278270

279271
for subdir in ['css', 'js']:
280-
try:
281-
makedirs('{}/{}'.format(htmlBaseDirectory, subdir))
282-
except OSError:
283-
pass
272+
makedirs(f'{htmlBaseDirectory}/{subdir}', exist_ok=True)
284273

285-
outFileName = '{}/index.html'.format(htmlBaseDirectory)
274+
outFileName = f'{htmlBaseDirectory}/index.html'
286275

287276
with open(outFileName, mode='w') as mainFile:
288277
mainFile.write(
289-
pageText.encode('ascii',
290-
'xmlcharrefreplace').decode('ascii'))
278+
pageText.encode('ascii', 'xmlcharrefreplace').decode('ascii')
279+
)
291280

292281
# copy the css and js files as well as general images
293-
fileName = \
294-
pkg_resources.resource_filename(__name__,
295-
"templates/style.css")
296-
copyfile(fileName, '{}/css/style.css'.format(htmlBaseDirectory))
297-
298-
fileName = \
299-
pkg_resources.resource_filename(__name__,
300-
"templates/index.js")
301-
copyfile(fileName, '{}/js/index.js'.format(htmlBaseDirectory))
302-
303-
fileName = \
304-
pkg_resources.resource_filename(__name__,
305-
"templates/mpas_logo.png")
306-
copyfile(fileName, '{}/mpas_logo.png'.format(htmlBaseDirectory))
307-
308-
fileName = \
309-
pkg_resources.resource_filename(__name__,
310-
"templates/config.png")
311-
copyfile(fileName, '{}/config.png'.format(htmlBaseDirectory))
312-
313-
with open('{}/complete.{}.cfg'.format(htmlBaseDirectory,
314-
runName), 'w') as configFile:
282+
resource_targets = [
283+
("style.css", "css/style.css"),
284+
("index.js", "js/index.js"),
285+
("mpas_logo.png", "mpas_logo.png"),
286+
("config.png", "config.png"),
287+
]
288+
for resource_name, target_path in resource_targets:
289+
package = 'mpas_analysis.shared.html.templates'
290+
fileName = resources.files(package).joinpath(resource_name)
291+
copyfile(str(fileName), f'{htmlBaseDirectory}/{target_path}')
292+
293+
outFileName = f'{htmlBaseDirectory}/complete.{runName}.cfg'
294+
with open(outFileName, 'w') as configFile:
315295
self.config.write(configFile)
316296

317297

@@ -386,11 +366,10 @@ def __init__(self, config, name, subdirectory, controlConfig=None):
386366
for templateName in ['page', 'quicklink', 'group', 'gallery', 'image',
387367
'subtitle']:
388368
# get template text
389-
fileName = pkg_resources.resource_filename(
390-
__name__,
391-
"templates/component_{}.html".format(templateName))
392-
393-
with open(fileName, 'r') as templateFile:
369+
package = 'mpas_analysis.shared.html.templates'
370+
resource = resources.files(package).joinpath(
371+
f'component_{templateName}.html')
372+
with resource.open('r') as templateFile:
394373
self.templates[templateName] = templateFile.read()
395374

396375
# start with no groups

mpas_analysis/shared/html/templates/__init__.py

Whitespace-only changes.

0 commit comments

Comments
 (0)