1
1
import os
2
2
import sys
3
- import tempfile
4
3
5
4
from . import abc as resources_abc
6
5
from . import trees
@@ -130,6 +129,15 @@ def read_text(package: Package,
130
129
return fp .read ()
131
130
132
131
132
+ def get (package : Package , resource : Resource ) -> trees .Traversable :
133
+ """
134
+ Get a Traversable resource from a package
135
+ """
136
+ resource = _normalize_path (resource )
137
+ package = _get_package (package )
138
+ return trees .from_package (package ) / resource
139
+
140
+
133
141
@contextmanager
134
142
def path (package : Package , resource : Resource ) -> Iterator [Path ]:
135
143
"""A context manager providing a file path object to the resource.
@@ -140,38 +148,14 @@ def path(package: Package, resource: Resource) -> Iterator[Path]:
140
148
raised if the file was deleted prior to the context manager
141
149
exiting).
142
150
"""
143
- resource = _normalize_path (resource )
144
- package = _get_package (package )
145
- reader = _get_resource_reader (package )
151
+ norm_resource = _normalize_path (resource )
152
+ reader = _get_resource_reader (_get_package (package ))
146
153
if reader is not None :
147
154
with suppress (FileNotFoundError ):
148
- yield Path (reader .resource_path (resource ))
155
+ yield Path (reader .resource_path (norm_resource ))
149
156
return
150
- # Fall-through for both the lack of resource_path() *and* if
151
- # resource_path() raises FileNotFoundError.
152
- package_directory = Path (package .__spec__ .origin ).parent
153
- file_path = package_directory / resource
154
- # If the file actually exists on the file system, just return it.
155
- if file_path .exists ():
156
- yield file_path
157
- return
158
-
159
- # Otherwise, it's probably in a zip file, so we need to create a temporary
160
- # file and copy the contents into that file, hence the contextmanager to
161
- # clean up the temp file resource.
162
- with open_binary (package , resource ) as fp :
163
- data = fp .read ()
164
- # Not using tempfile.NamedTemporaryFile as it leads to deeper 'try'
165
- # blocks due to the need to close the temporary file to work on
166
- # Windows properly.
167
- fd , raw_path = tempfile .mkstemp ()
168
- try :
169
- os .write (fd , data )
170
- os .close (fd )
171
- yield Path (raw_path )
172
- finally :
173
- with suppress (FileNotFoundError ):
174
- os .remove (raw_path )
157
+ with trees .as_file (get (package , resource )) as res :
158
+ yield res
175
159
176
160
177
161
def is_resource (package : Package , name : str ) -> bool :
0 commit comments