Skip to content

Instantly share code, notes, and snippets.

@motebaya
Created January 8, 2025 01:57
Show Gist options
  • Save motebaya/57f2c938a22fb3cc2ceba9509c2af022 to your computer and use it in GitHub Desktop.
Save motebaya/57f2c938a22fb3cc2ceba9509c2af022 to your computer and use it in GitHub Desktop.
simple way for check or update python library to latest version based pypi.org api
#!/usr/bin/env python3
# 10.10.2024 - python module version check
# © @github.com/motebaya
from typing import Any, Dict
import importlib.metadata
import requests, subprocess, sys
class ModuleManager:
@staticmethod
def get_latest_module(modulename: str) -> Any:
"""fresh install module
:param str modulename: _description_
:raises Exception: _description_
:return Any: _description_
"""
try:
print(f"? installing module: {modulename}")
subprocess.check_call([
sys.executable, '-m', 'pip', 'install', modulename
])
except subprocess.CalledProcessError as e:
raise Exception(str(e))
@staticmethod
def update_current_module(modulename: str) -> None:
"""update current installed module to latest version
:param str modulename: _description_
:raises Exception: _description_
"""
try:
print(f'? updating module: {modulename}')
subprocess.check_call([
sys.executable, '-m', 'pip', 'install', '--upgrade', modulename
])
except subprocess.CalledProcessError as e:
raise Exception(str(e))
@staticmethod
def check_current_version(modulename: str) -> str:
"""check current version installed
:param str modulename: _description_
:return str: _description_
"""
try:
return importlib.metadata.version(modulename)
except importlib.metadata.PackageNotFoundError:
return
@staticmethod
def get_latest_version(modulename: str) -> Dict[str, Any]:
current_version = ModuleManager.check_current_version(modulename)
if current_version:
print("? checking latest version update..")
module = requests.get(
f'https://pypi.org/pypi/{modulename}/json', headers={
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36',
'Content-Type': 'application/json'
}
).json().get('info')
if module:
latest_version = module['version']
if latest_version == current_version:
print(f'! good, you have installed {modulename} with latest version: {latest_version}!')
return True
print(f"? current version: {current_version}, new version detected: {latest_version}..")
return ModuleManager.update_current_module(
modulename
)
else:
raise ModuleNotFoundError(
f'no module found for name: {modulename}'
)
else:
ModuleManager.get_latest_module(modulename)
if __name__=="__main__":
ModuleManager.get_latest_version(
'requests'
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment