from pip._internal import main as _main import importlib def _import(name, module, ver=None): try: globals()[name] = importlib.import_module(module) except ImportError: try: if ver is None: _main(['install', module]) else: _main(['install', '{}=={}'.format(module, ver)]) globals()[name] = importlib.import_module(module) except: print("can't import: {}".format(module)) _import('psutil','psutil', '5.7.0')