Python equivalent to Java's Class.getResource [duplicate]
I have some XML files on my PYTHONPATH that I would like to load using their path on the PYTHONPATH, rather than their (relative or absolute) path on the filesystem. I could simply inline them as strings in a Python module (yay multiline string literals), and then load them using a regular import
statement, but I'd like to keep them separated out as regular XML files, if possible. In Java world, the solution to this would be to use the Class.getResource method, and I'm wondering if something similar exists in Python.
Take a look at pkg_resources, it includes apis for the inclusion to generic resources. It is thought to work with python eggs and so it could be much more of you need.
Just an example taken from the doc:
import pkg_resources
my_data = pkg_resources.resource_string(__name__, "foo.dat")
I don't know of anything built-in, but something like the following should emulate the behavior (assuming the files are on a local disk -- I don't believe that PYTHONPATH support non-local file paths, whereas the Java classpath can contain URLs to remote resources).
def get_pypath_resource(resource_name):
for path in sys.path:
if os.path.exists(os.path.join(path, resource_name)):
return os.path.join(path, resource_name)
raise Exception('Resource %s could not be found' % resource_name)
精彩评论