Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit cafbc10

Browse files
authored
Merge pull request #15775 from anntzer/pathlib
Some pathlibification.
2 parents d417753 + 52136a7 commit cafbc10

File tree

10 files changed

+39
-55
lines changed

10 files changed

+39
-55
lines changed

examples/misc/image_thumbnail_sgskip.py

Lines changed: 15 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -3,34 +3,30 @@
33
Image Thumbnail
44
===============
55
6-
You can use matplotlib to generate thumbnails from existing images.
6+
You can use Matplotlib to generate thumbnails from existing images.
77
Matplotlib relies on Pillow_ for reading images, and thus supports all formats
88
supported by Pillow.
99
1010
.. _Pillow: http://python-pillow.org/
1111
"""
1212

13-
# build thumbnails of all images in a directory
13+
from argparse import ArgumentParser
14+
from pathlib import Path
1415
import sys
15-
import os
16-
import glob
1716
import matplotlib.image as image
1817

1918

20-
if len(sys.argv) != 2:
21-
print('Usage: python %s IMAGEDIR' % __file__)
22-
raise SystemExit
23-
indir = sys.argv[1]
24-
if not os.path.isdir(indir):
25-
print('Could not find input directory "%s"' % indir)
26-
raise SystemExit
19+
parser = ArgumentParser(
20+
description="Build thumbnails of all images in a directory.")
21+
parser.add_argument("imagedir", type=Path)
22+
args = parser.parse_args()
23+
if not args.imagedir.isdir():
24+
sys.exit(f"Could not find input directory {args.imagedir}")
2725

28-
outdir = 'thumbs'
29-
if not os.path.exists(outdir):
30-
os.makedirs(outdir)
26+
outdir = Path("thumbs")
27+
outdir.mkdir(parents=True, exist_ok=True)
3128

32-
for fname in glob.glob(os.path.join(indir, '*.png')):
33-
basedir, basename = os.path.split(fname)
34-
outfile = os.path.join(outdir, basename)
35-
fig = image.thumbnail(fname, outfile, scale=0.15)
36-
print('saved thumbnail of %s to %s' % (fname, outfile))
29+
for path in args.imagedir.glob("*.png"):
30+
outpath = outdir / path.name
31+
fig = image.thumbnail(path, outpath, scale=0.15)
32+
print(f"saved thumbnail of {path} to {outpath}")

examples/tests/backend_driver_sgskip.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -458,6 +458,7 @@ def parse_options():
458458
result.dirs[result.dirs.index('pylab_examples')] = 'pylab'
459459
return result
460460

461+
461462
if __name__ == '__main__':
462463
times = {}
463464
failures = {}

examples/user_interfaces/mpl_with_glade3_sgskip.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,11 @@
55
66
"""
77

8-
import os
8+
from pathlib import Path
99

1010
import gi
1111
gi.require_version('Gtk', '3.0')
1212
from gi.repository import Gtk
13-
1413
from matplotlib.figure import Figure
1514
from matplotlib.backends.backend_gtk3agg import (
1615
FigureCanvasGTK3Agg as FigureCanvas)
@@ -24,9 +23,9 @@ def on_window1_destroy(self, widget):
2423

2524
def main():
2625
builder = Gtk.Builder()
27-
builder.add_objects_from_file(os.path.join(os.path.dirname(__file__),
28-
"mpl_with_glade3.glade"),
29-
("window1", ""))
26+
builder.add_objects_from_file(
27+
str(Path(__file__).parent / "mpl_with_glade3.glade"),
28+
("window1", ""))
3029
builder.connect_signals(Window1Signals())
3130
window = builder.get_object("window1")
3231
sw = builder.get_object("scrolledwindow1")

lib/matplotlib/afm.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,6 @@
3737
import logging
3838
import re
3939

40-
4140
from ._mathtext_data import uni2type1
4241

4342

lib/matplotlib/dviread.py

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
from functools import lru_cache, partial, wraps
2323
import logging
2424
import os
25+
from pathlib import Path
2526
import re
2627
import struct
2728
import textwrap
@@ -203,12 +204,9 @@ def __init__(self, filename, dpi):
203204

204205
def _get_baseline(self, filename):
205206
if rcParams['text.latex.preview']:
206-
base, ext = os.path.splitext(filename)
207-
baseline_filename = base + ".baseline"
208-
if os.path.exists(baseline_filename):
209-
with open(baseline_filename, 'rb') as fd:
210-
l = fd.read().split()
211-
height, depth, width = l
207+
baseline = Path(filename).with_suffix(".baseline")
208+
if baseline.exists():
209+
height, depth, width = baseline.read_bytes().split()
212210
return float(depth)
213211
return None
214212

lib/matplotlib/image.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1435,8 +1435,7 @@ def imread(fname, format=None):
14351435
if len(parsed.scheme) > 1:
14361436
ext = 'png'
14371437
else:
1438-
basename, ext = os.path.splitext(fname)
1439-
ext = ext.lower()[1:]
1438+
ext = Path(fname).suffix.lower()[1:]
14401439
elif hasattr(fname, 'geturl'): # Returned by urlopen().
14411440
# We could try to parse the url's path and use the extension, but
14421441
# returning png is consistent with the block above. Note that this
@@ -1445,8 +1444,7 @@ def imread(fname, format=None):
14451444
# value "<urllib response>").
14461445
ext = 'png'
14471446
elif hasattr(fname, 'name'):
1448-
basename, ext = os.path.splitext(fname.name)
1449-
ext = ext.lower()[1:]
1447+
ext = Path(fname.name).suffix.lower()[1:]
14501448
else:
14511449
ext = 'png'
14521450
else:

lib/matplotlib/sphinxext/mathmpl.py

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import hashlib
2-
import os
2+
from pathlib import Path
33

44
from docutils import nodes
55
from docutils.parsers.rst import Directive, directives
@@ -60,7 +60,7 @@ def run(self):
6060
def latex2png(latex, filename, fontset='cm'):
6161
latex = "$%s$" % latex
6262
with mpl.rc_context({'mathtext.fontset': fontset}):
63-
if os.path.exists(filename):
63+
if Path(filename).exists():
6464
depth = mathtext_parser.get_depth(latex, dpi=100)
6565
else:
6666
try:
@@ -80,11 +80,9 @@ def latex2html(node, source):
8080
name = 'math-{}'.format(
8181
hashlib.md5((latex + fontset).encode()).hexdigest()[-10:])
8282

83-
destdir = os.path.join(setup.app.builder.outdir, '_images', 'mathmpl')
84-
if not os.path.exists(destdir):
85-
os.makedirs(destdir)
86-
dest = os.path.join(destdir, '%s.png' % name)
87-
path = '/'.join((setup.app.builder.imgpath, 'mathmpl'))
83+
destdir = Path(setup.app.builder.outdir, '_images', 'mathmpl')
84+
destdir.mkdir(parents=True, exist_ok=True)
85+
dest = destdir / f'{name}.png'
8886

8987
depth = latex2png(latex, dest, fontset)
9088

@@ -97,7 +95,8 @@ def latex2html(node, source):
9795
else:
9896
style = ''
9997

100-
return '<img src="%s/%s.png" %s%s/>' % (path, name, cls, style)
98+
return (f'<img src="{setup.app.builder.imgpath}/mathmpl/{name}.png"'
99+
f' {cls}{style}/>')
101100

102101

103102
def setup(app):

lib/matplotlib/tests/test_font_manager.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -179,8 +179,7 @@ def test_user_fonts_win32():
179179
os.makedirs(user_fonts_dir)
180180

181181
# Copy the test font to the user font directory
182-
shutil.copyfile(os.path.join(os.path.dirname(__file__), font_test_file),
183-
os.path.join(user_fonts_dir, font_test_file))
182+
shutil.copy(Path(__file__).parent / font_test_file, user_fonts_dir)
184183

185184
# Now, the font should be available
186185
fonts = findSystemFonts()

lib/matplotlib/tests/test_png.py

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
from io import BytesIO
2-
import glob
3-
import os
2+
from pathlib import Path
43

54
import pytest
65

@@ -11,11 +10,8 @@
1110

1211
@image_comparison(['pngsuite.png'], tol=0.03)
1312
def test_pngsuite():
14-
dirname = os.path.join(
15-
os.path.dirname(__file__),
16-
'baseline_images',
17-
'pngsuite')
18-
files = sorted(glob.iglob(os.path.join(dirname, 'basn*.png')))
13+
files = sorted(
14+
(Path(__file__).parent / "baseline_images/pngsuite").glob("basn*.png"))
1915

2016
plt.figure(figsize=(len(files), 2))
2117

lib/mpl_toolkits/tests/__init__.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,8 @@
1-
import os
1+
from pathlib import Path
22

33

44
# Check that the test directories exist
5-
if not os.path.exists(os.path.join(
6-
os.path.dirname(__file__), 'baseline_images')):
5+
if not (Path(__file__).parent / "baseline_images").exists():
76
raise IOError(
87
'The baseline image directory does not exist. '
98
'This is most likely because the test data is not installed. '

0 commit comments

Comments
 (0)