简体   繁体   中英

Get parsed entries for Distribution/module metada from PKG-INFO (Python pkg_resources)

I'm currently using code similar to this

# Returns PKG-INFO in "email format", meaning it looks a little like this:
#   Name: some_python_module
#   Version: 1.2.3
dist = pkg_resources.get_distribution('some_python_module')
pkginfo = dist.get_metadata(dist.PKG_INFO)

d = dict(line.split(': ', 1) for line in pkginfo.split('\n') if ': ' in line)
print(d['Name'])

I'm wondering if there is a "clean" way to do this key lookup for a Distribution object?

Note I am using custom properties here so doing dist.project_name or dist.version are not enough in my particular case.

Stolen from _parsed_pkg_info in DistInfoDistribution :

dist = pkg_resources.get_distribution('some_python_module')
pkginfo = dist.get_metadata(dist.PKG_INFO)

parsed = email.parser.Parser().parsestr(pkginfo)
print(parsed['Name'])

Not sure why this method is not in Distribution as it appears to work for both DistInfoDistribution and EggInfoDistribution -- this is what dist.PKG_INFO is for by the way, this variable differs between those two ( 'METADATA' for .dist-info and 'PKG-INFO' for .egg-info ).

Little note: parsestr returns a FeedParser object which outputs the parsed input feed when you call print on it -- do not get confused by this, it's not a str . Also note that spaces are not allowed in key names by the RFC and lead to silent parser errors!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM