Last active
November 26, 2017 10:07
-
-
Save frodo821/6e4b0750bbff279b1aab498b77837d20 to your computer and use it in GitHub Desktop.
依存関係解決__import__ラッパー関数
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#-*- coding:utf-8; -*- | |
#DependencyResolvor.py | |
""" | |
ModuleManager detail implement. | |
""" | |
import os.path as path | |
from os import mkdir | |
import sys | |
import subprocess as sp | |
__all__=["__doc__", "__name__", "__all__","resolve", "does_module_exist"] | |
TARGET_DIR = path.join(path.dirname(__file__), 'modules')) | |
def get_progress(): | |
c = 5000 | |
while True: | |
for y in ['\\'] * c + ['|'] * c + ['/'] * c + ['―'] * c: | |
yield y | |
def resolve_dependencies(mod_name: str, mod_distname = None): | |
""" | |
Module dependency resolvor | |
""" | |
if mod_distname is None: | |
mod_distname = mod_name | |
if not path.exists(TARGET_DIR): | |
mkdir(TARGET_DIR) | |
try: | |
p = get_progress() | |
sproc = sp.Popen("pip install {0} --target={1} --quiet"\ | |
.format(mod_distname, TARGET_DIR, stdout=None, stderr=None) | |
while sproc.poll() == None: | |
mes = "Resolving dependencies: installing {0}...{1}".format(mod_name, next(p)) | |
print(mes, end='\r') | |
print('\n') | |
except sp.CalledProcessError as err: | |
print(err, file=sys.stderr) | |
return False | |
return True | |
def does_module_exist(mod_name: str): | |
""" | |
Dose the module mod_name exist? | |
""" | |
try: | |
__import__(mod_name) | |
except ModuleNotFoundError: | |
return False | |
return True | |
def resolve(mod_name: str, globals: dict, mod_distname = None): | |
""" | |
module dependencies resolving and importing. | |
""" | |
if not does_module_exist(mod_name): | |
if not resolve_dependencies(mod_name): | |
raise EnvironmentError( | |
"Could not continue program, because failed resolving dependencies.") | |
try: | |
globals[mod_name] = __import__(mod_name, globals) | |
except ModuleNotFoundError: | |
print(sys.path) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment