Skip to content

Instantly share code, notes, and snippets.

@AlJohri
Last active December 5, 2016 20:58
Show Gist options
  • Select an option

  • Save AlJohri/5d0190ee85d008bb48e2740b052981f6 to your computer and use it in GitHub Desktop.

Select an option

Save AlJohri/5d0190ee85d008bb48e2740b052981f6 to your computer and use it in GitHub Desktop.
import subprocess
def import_thirdparty_module(libname, importname=None):
if not importname:
importname = libname
# http://stackoverflow.com/questions/25491541/python3-json-post-request-without-requests-library
try:
lib = __import__(importname)
except ImportError:
print("error: missing dependency '{libname}'\n"
"to install, run: pip3 install {libname}\n"
"would you like me to install it for you?\n"
"I will be using the pip3 command located at:".format(libname=libname))
subprocess.run("which pip", shell=True)
yes_no = input("Install? [y/n] ")
if yes_no.lower() in ["yes", "y"]:
ret = subprocess.run("pip3 install {}".format(libname), shell=True)
if ret.returncode == 0:
print("install successful. please rerun your command")
else:
print("install unsuccessful")
sys.exit()
return lib
@AlJohri

AlJohri commented Dec 5, 2016

Copy link
Copy Markdown
Author

Example usage:

yaml = import_thirdparty_module('pyaml', 'yaml')
git = import_thirdparty_module('GitPython', 'git')
requests = import_thirdparty_module('requests')

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment