如何使用importlib.resources.path(package, resource)?

How to use importlib.resources.path(package, resource)?

我正在使用以下代码创建 _GeneratorContextManager。

try:
    import importlib.resources as pkg_resources
except ImportError:
    # Try backported to PY<37 `importlib_resources`.
    import importlib_resources as pkg_resources
from . import file_resources

package_path= pkg_resources.path(file_resources, "IWNLP.Lemmatizer_20181001.json")

这是变量 package_path 的调试器视图。

现在我想将文件"IWNLP.Lemmatizer_20181001.json"的路径传递给另一个函数:

 lemmatizer = IWNLPWrapper(lemmatizer_path=package_path)

文档说 "The context manager provides a pathlib.Path object"。如何访问 pathlib.Path 对象?

with pkg_resources.path(file_resources, "IWNLP.Lemmatizer_20181001.json") as p:
    package_path = p

p 是 PosixPath 类型的变量,包含文件 IWNLP.Lemmatizer_20181001.json 的完整路径。参见 https://docs.python.org/3.8/library/pathlib.html#pathlib.Path