自动安装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")



posted @ 2021-07-15 14:51  liuyang9643  阅读(98)  评论(0编辑  收藏  举报