Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
275 views
in Technique[技术] by (71.8m points)

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('
') 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.

question from:https://stackoverflow.com/questions/65887224/get-parsed-entries-for-distribution-module-metada-from-pkg-info-python-pkg-reso

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...