Skip to content

Instantly share code, notes, and snippets.

@yaleman
Created March 22, 2021 01:24
Show Gist options
  • Save yaleman/4a2d81273b739313d88401e5b434b6fa to your computer and use it in GitHub Desktop.
Save yaleman/4a2d81273b739313d88401e5b434b6fa to your computer and use it in GitHub Desktop.
Try importing a package and then attempt to install it if it's not there
#!/usr/bin/env python3
# This'll try and install the required packages.
for import_attempt in range(100):
try:
import requests
import click
from loguru import logger
continue
except ImportError as error_message:
if error_message.name:
package = error_message.name
response = input(f"You don't have {package} installed, do you want me to try and install it? (y|(es)) ")
if response.strip() and response.strip().lower() not in ('y','yes'):
sys.exit("Ok, quitting now.")
try:
pipcmd = ['install', '--user', package]
import pip._internal.commands
command = pip._internal.commands.create_command('install')
if command.main(['--user', package]):
sys.exit(f"Failed to install {package}, bailing.")
except ImportError:
sys.exit(f"You don't have pip installed and I can't import {package}, quitting")
except Exception as e:
sys.exit(f"pip error - bailing: {e}")
if import_attempt > 20:
sys.exit("Too many attempts to install packages, bailing.")
print("well, you got this far...")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment