Note: I am NOT looking for a way to interrogate installed packages in the virtual environment and do not want to load packages in order to parse them.
I'm looking for a way to parse meta data from files [wheels and tar.gz] downloaded from pypi. The format isn't so complex so I'm not really against writing my own. But given that python must be parsing this info inside importlib I wanted to see if theres a way that doesn't involve re-inventing the wheel.
I can see that importlib.metadata lets me get this information for installed pacakges. But I want to do this for a lot of versions of the same packages; many of which may not be compatible with the current virtual environment or even system architecture.
Does python (>=3.10) offer any interface for parsing wheel and tar.gz metadata without actually installing it into the virtual environment?
This code searches for the METADATA file within the .whl file using the zipfile built-in library. The metadata is then parsed using email.parser to obtain a Message object, which can be accessed as a dictionary.
import zipfile
import email.parser
def get_metadata(path:str) -> str:
# Open the file using zipfile
with zipfile.ZipFile(path) as archive:
# Find and read the METADATA file from the archive
metadata_path = [file.filename for file in archive.filelist if "METADATA" in file.filename][0]
metadata = archive.read(metadata_path).decode("utf-8")
return email.parser.Parser().parsestr(metadata)
# Path to the wheel or tar.gz file
file_path = "numpy-1.25.2.whl"
METADATA = get_metadata(file_path)
print("Name: ", METADATA["name"])
print("Version: ", METADATA["version"])
print("Summary: ", METADATA["summary"])
Output:
Name: numpy
Version: 1.25.2
Summary: Fundamental package for array computing in Python
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With