In the following script, I am trying to infer if the modules are managed by a conda environment or not and based on that, I am trying to auto install and import the modules. [I skipped around 5 to 6 imports to keep it short for the sake of this example].

It would be great if someone can give me some pointers if I have made any mistakes in my following code.

import importlib
import os
import subprocess
import sys

def package_install(package, is_conda):
    """ Installs missing modules. """
    install_env = "conda" if is_conda else "pip"
    conda_call = [install_env, "install", "-y", package]
    pip_call = [sys.executable, "-m", install_env, "install", package]
    install_call = conda_call if is_conda else pip_call

    except Exception as err:
        print(f'Unable to install the module using {install_env}:\n{repr(err)}')

# Check if the packages are managed with conda environment
is_conda = os.path.exists(os.path.join(sys.prefix, 'conda-meta'))

    import matplotlib as plt
except ImportError:
    package_install("matplotlib", is_conda)
    plt = importlib.import_module("matplotlib")
    import descartes as des
except ImportError:
    package_install("descartes", is_conda)
    des = importlib.import_module("descartes")


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.