Skip to content

Instantly share code, notes, and snippets.

@rhoconlinux
Created January 17, 2024 21:44
Show Gist options
  • Save rhoconlinux/47ba87d380f9cc971e2c5208f4b8a4ea to your computer and use it in GitHub Desktop.
Save rhoconlinux/47ba87d380f9cc971e2c5208f4b8a4ea to your computer and use it in GitHub Desktop.
pip_check_v2.py
import importlib.metadata
import subprocess
import sys
def check_and_install(package_or_file, file=False):
if file:
with open(package_or_file, 'r') as file:
packages = file.readlines()
else:
packages = [package_or_file]
for package in packages:
package = package.strip()
try:
importlib.metadata.version(package)
print(f"Package {package} installed ok ... ✅")
except importlib.metadata.PackageNotFoundError:
subprocess.check_call([sys.executable, '-m', 'pip', 'install', package])
# Usage
#check_and_install("langchain") # For a single package
#check_and_install("requirements.txt", file=True) # For a file
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment