自动安装Python包

def install_package(package, version="upgrade"):
    from sys import executable
    from subprocess import check_call
    result = False
    if version.lower() == "upgrade":
        result = check_call([executable, "-m", "pip", "install", package, "--upgrade", "--user"])
    else:
        from pkg_resources import get_distribution
        current_package_version = None
        try:
            current_package_version = get_distribution(package)
        except Exception:
            pass
        if current_package_version is None or current_package_version != version:
            installation_sign = "==" if ">=" not in version else ""
            result = check_call([executable, "-m", "pip", "install", package + installation_sign + version, "--user"])
    return result


try:
    from gevent.socket import wait_read
except ImportError:
    print("gevent library not found - installing...")
    install_package("gevent==1.4.0")

try:
    import paramiko
except ImportError:
    print("paramiko library not found - installing...")
    install_package("paramiko==2.7.2")

try:
    import psycopg2
except ImportError:
    print("psycopg2 library not found - installing...")
    install_package("psycopg2==2.9.1")



上一篇:linux和window设置 pip 镜像源 、最实用的环境下载加速设置 ——【一文读懂】


下一篇:开源Math.NET基础数学类库使用(04)C#解析Matrix Marke数据格式