如何使用PIP编程(从我的代码)安装PIP模块?

发布于 2025-01-30 20:03:23 字数 168 浏览 3 评论 0 原文

我需要从

是否有某些模块或 distutils distribute pip 等)功能,使我可以执行诸如 pypi之类的东西。 install('请求')和请求将安装到我的Virtualenv中?

I need to install a package from PyPI straight within my script.

Is there maybe some module or distutils (distribute, pip, etc.) feature which allows me to just execute something like pypi.install('requests') and requests will be installed into my virtualenv?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(13

月下凄凉 2025-02-06 20:03:24

对于安装多个软件包,我使用 setup.py.py 文件,其中包括以下代码:

import sys
import subprocess
import pkg_resources

required  = {'numpy', 'pandas', '<etc>'} 
installed = {pkg.key for pkg in pkg_resources.working_set}
missing   = required - installed

if missing:
    # implement pip as a subprocess:
    subprocess.check_call([sys.executable, '-m', 'pip', 'install', *missing])

For installing multiple packages, I am using a setup.py file with the following code:

import sys
import subprocess
import pkg_resources

required  = {'numpy', 'pandas', '<etc>'} 
installed = {pkg.key for pkg in pkg_resources.working_set}
missing   = required - installed

if missing:
    # implement pip as a subprocess:
    subprocess.check_call([sys.executable, '-m', 'pip', 'install', *missing])
我恋#小黄人 2025-02-06 20:03:24

使用:

import os
os.system('pip install requests')

我尝试了以上用于临时解决方案的方法,而不是更改 docker file docker file 。

Use:

import os
os.system('pip install requests')

I tried the above for a temporary solution instead of changing a Docker file.

浅沫记忆 2025-02-06 20:03:24

如果您想要一个更有效的答案,以扩展 subprocess.check_call 。您可以首先使用 pkg_resources 检查是否已经满足了需求。

这适用于不同的需求specifiers 很好。例如,&gt; = ==

import sys
import subprocess
import pkg_resources
from pkg_resources import DistributionNotFound, VersionConflict

def should_install_requirement(requirement):
    should_install = False
    try:
        pkg_resources.require(requirement)
    except (DistributionNotFound, VersionConflict):
        should_install = True
    return should_install


def install_packages(requirement_list):
    try:
        requirements = [
            requirement
            for requirement in requirement_list
            if should_install_requirement(requirement)
        ]
        if len(requirements) > 0:
            subprocess.check_call([sys.executable, "-m", "pip", "install", *requirements])
        else:
            print("Requirements already satisfied.")

    except Exception as e:
        print(e)

示例用法:

requirement_list = ['requests', 'httpx==0.18.2']
install_packages(requirement_list)

“

相关信息:堆栈溢出问题:58612272

If you want a more efficient answer that expands on subprocess.check_call. You can first check if the requirement has already been met using pkg_resources.

This works for different requirement specifiers which is nice. E.g., >=, ==:

import sys
import subprocess
import pkg_resources
from pkg_resources import DistributionNotFound, VersionConflict

def should_install_requirement(requirement):
    should_install = False
    try:
        pkg_resources.require(requirement)
    except (DistributionNotFound, VersionConflict):
        should_install = True
    return should_install


def install_packages(requirement_list):
    try:
        requirements = [
            requirement
            for requirement in requirement_list
            if should_install_requirement(requirement)
        ]
        if len(requirements) > 0:
            subprocess.check_call([sys.executable, "-m", "pip", "install", *requirements])
        else:
            print("Requirements already satisfied.")

    except Exception as e:
        print(e)

Example usage:

requirement_list = ['requests', 'httpx==0.18.2']
install_packages(requirement_list)

Demo

Relevant information: Stack Overflow question: 58612272

韶华倾负 2025-02-06 20:03:24

您可以使用“ install_requires”选项定义您自己软件包的依赖模块。

如果您的软件包需要生成一些控制台脚本,则可以使用“ console_scripts”输入点,以生成包装脚本
在“ bin”文件夹中(例如,虚拟环境的环境)。

You define the dependent module inside the setup.py of your own package with the "install_requires" option.

If your package needs to have some console script generated then you can use the "console_scripts" entry point in order to generate a wrapper script that will be placed
within the 'bin' folder (e.g. of your virtualenv environment).

寒冷纷飞旳雪 2025-02-06 20:03:24

有条件地安装带有精确版本的多个软件包,我一直在@tanmay Shrivastava的答案上使用这种模式。

import sys
from subprocess import run, PIPE, STDOUT
import pkg_resources

def run_cmd(cmd):
    ps = run(cmd, stdout=PIPE, stderr=STDOUT, shell=True, text=True)
    print(ps.stdout)


# packages to be conditionally installed with exact version
required = {"click==8.0.1", "semver==3.0.0.dev2"}
installed = {f"{pkg.key}=={pkg.version}" for pkg in pkg_resources.working_set}
missing = required - installed

if missing:
    run_cmd(f'pip install --ignore-installed {" ".join([*missing])}')

To conditionally install multiple packages with exact version, I've been using this pattern basing on @Tanmay Shrivastava's answer:

import sys
from subprocess import run, PIPE, STDOUT
import pkg_resources

def run_cmd(cmd):
    ps = run(cmd, stdout=PIPE, stderr=STDOUT, shell=True, text=True)
    print(ps.stdout)


# packages to be conditionally installed with exact version
required = {"click==8.0.1", "semver==3.0.0.dev2"}
installed = {f"{pkg.key}=={pkg.version}" for pkg in pkg_resources.working_set}
missing = required - installed

if missing:
    run_cmd(f'pip install --ignore-installed {" ".join([*missing])}')
灼痛 2025-02-06 20:03:24
    import pip

try:
    import imaplib
    import email
    import pandas as pd
    # for hiding password
    from pathlib import Path
    from dotenv import load_dotenv
    import os
    import requests
    # 
    from collections import defaultdict
    from itertools import permutations,combinations
except Exception as e:
    print(e)
    e = str(e).split(' ')[-1].replace("'","")
    pip.main(['install', e])
    import pip

try:
    import imaplib
    import email
    import pandas as pd
    # for hiding password
    from pathlib import Path
    from dotenv import load_dotenv
    import os
    import requests
    # 
    from collections import defaultdict
    from itertools import permutations,combinations
except Exception as e:
    print(e)
    e = str(e).split(' ')[-1].replace("'","")
    pip.main(['install', e])
你在看孤独的风景 2025-02-06 20:03:24

我不喜欢所有建议的选项,因此我写了 library 为此。

安装它:

pip install instld

使用上下文管理器:

import installed

with installed('some_package'):
  import some_module

要了解有关库的更多信息,请按照我上面给出的链接。它允许您在一个程序中使用两个不同版本的同一库,例如,彼此之间不兼容的库。

I didn't like all the suggested options and I wrote my library for this.

Install it:

pip install instld

And use a context manager:

import installed

with installed('some_package'):
  import some_module

To learn more about the library, follow the link I gave above. It allows you to use two different versions of the same library in one program, or, for example, libraries that are incompatible with each other.

十二 2025-02-06 20:03:24

尝试以下。到目前为止,这是对我有用的最好的。

首先安装4个,然后提及“必需” 列表中的新:

import pkg_resources
import subprocess
import sys
import os

REQUIRED = {
  'spacy', 'scikit-learn', 'numpy', 'pandas', 'torch',
  'pyfunctional', 'textblob', 'seaborn', 'matplotlib'
}

installed = {pkg.key for pkg in pkg_resources.working_set}
missing = REQUIRED - installed

if missing:
    python = sys.executable
    subprocess.check_call([python, '-m', 'pip', 'install', *missing], stdout=subprocess.DEVNULL)

Try the below. So far, it was the best that worked for me.

Install the 4 ones first and then mention the new ones in the "REQUIRED" list:

import pkg_resources
import subprocess
import sys
import os

REQUIRED = {
  'spacy', 'scikit-learn', 'numpy', 'pandas', 'torch',
  'pyfunctional', 'textblob', 'seaborn', 'matplotlib'
}

installed = {pkg.key for pkg in pkg_resources.working_set}
missing = REQUIRED - installed

if missing:
    python = sys.executable
    subprocess.check_call([python, '-m', 'pip', 'install', *missing], stdout=subprocess.DEVNULL)
你是暖光i 2025-02-06 20:03:23

从脚本安装软件包的正式建议方法是通过子过程调用PIP的命令行接口。 此处提供的大多数其他答案不受PIP 。此外,自PIP V10以来,所有代码已移至 pip._internal ,以便向用户清楚地表明,不允许使用PIP的程序使用。

使用 sys.executable 确保您将调用与当前运行时关联的相同 pip

import subprocess
import sys

def install(package):
    subprocess.check_call([sys.executable, "-m", "pip", "install", package])

The officially recommended way to install packages from a script is by calling pip's command-line interface via a subprocess. Most other answers presented here are not supported by pip. Furthermore since pip v10, all code has been moved to pip._internal precisely in order to make it clear to users that programmatic use of pip is not allowed.

Use sys.executable to ensure that you will call the same pip associated with the current runtime.

import subprocess
import sys

def install(package):
    subprocess.check_call([sys.executable, "-m", "pip", "install", package])
同展鸳鸯锦 2025-02-06 20:03:23

您也可以使用类似的东西:

import pip

def install(package):
    if hasattr(pip, 'main'):
        pip.main(['install', package])
    else:
        pip._internal.main(['install', package])

# Example
if __name__ == '__main__':
    install('argh')

You can also use something like:

import pip

def install(package):
    if hasattr(pip, 'main'):
        pip.main(['install', package])
    else:
        pip._internal.main(['install', package])

# Example
if __name__ == '__main__':
    install('argh')
第几種人 2025-02-06 20:03:23

如果要使用 pip 安装所需的软件包并在安装后导入它,则可以使用此代码:

def install_and_import(package):
    import importlib
    try:
        importlib.import_module(package)
    except ImportError:
        import pip
        pip.main(['install', package])
    finally:
        globals()[package] = importlib.import_module(package)


install_and_import('transliterate')

如果您以用户的身份安装了软件包,则可以遇到无法仅导入软件包的问题。请参阅如何刷新sys.path?以获取更多信息。

If you want to use pip to install required package and import it after installation, you can use this code:

def install_and_import(package):
    import importlib
    try:
        importlib.import_module(package)
    except ImportError:
        import pip
        pip.main(['install', package])
    finally:
        globals()[package] = importlib.import_module(package)


install_and_import('transliterate')

If you installed a package as a user you can encounter the problem that you cannot just import the package. See How to refresh sys.path? for additional information.

她如夕阳 2025-02-06 20:03:23

这应该有效:

import subprocess
import sys

def install(name):
    subprocess.call([sys.executable, '-m', 'pip', 'install', name])

This should work:

import subprocess
import sys

def install(name):
    subprocess.call([sys.executable, '-m', 'pip', 'install', name])
孤星 2025-02-06 20:03:23

我在

import subprocess
import sys

try:
    import pandas as pd
except ImportError:
    subprocess.check_call([sys.executable, "-m", "pip", "install", 'pandas'])
finally:
    import pandas as pd

I added some exception handling to Aaron's answer.

import subprocess
import sys

try:
    import pandas as pd
except ImportError:
    subprocess.check_call([sys.executable, "-m", "pip", "install", 'pandas'])
finally:
    import pandas as pd
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文