python importlib_metadata,如何找到给定模块的python包元数据信息

I'm trying to retrieve metadata information for a python package given the name of the module.

I can use importlib-metadata to retrieve the information, but in some cases the top-level module name is not the same as the package name.

example:

>>> importlib_metadata.metadata('zmq')['License']

Traceback (most recent call last):

File "", line 1, in

File "c:\Users\xxxxx\AppData\Local\Programs\Python\Python37\Lib\site-packages\importlib_metadata\__init__.py", line 499, in metadata

return Distribution.from_name(distribution_name).metadata

File "c:\Users\xxxxx\AppData\Local\Programs\Python\Python37\Lib\site-packages\importlib_metadata\__init__.py", line 187, in from_name

raise PackageNotFoundError(name)

importlib_metadata.PackageNotFoundError: zmq

>>> importlib_metadata.metadata('pyzmq')['License']

'LGPL+BSD'

解决方案

I believe something like the following should work:

#!/usr/bin/env python3

import importlib.util

import pathlib

import importlib_metadata

def get_distribution(file_name):

result = None

for distribution in importlib_metadata.distributions():

try:

relative = (

pathlib.Path(file_name)

.relative_to(distribution.locate_file(''))

)

except ValueError:

pass

else:

if relative in distribution.files:

result = distribution

return result

def alpha():

file_name = importlib.util.find_spec('easy_install').origin

distribution = get_distribution(file_name)

print("alpha", distribution.metadata['Name'])

def bravo():

file_name = importlib_metadata.__file__

distribution = get_distribution(file_name)

print("bravo", distribution.metadata['Name'])

if __name__ == '__main__':

alpha()

bravo()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值