在代码中安装python模块

问题:在代码中安装python模块

我需要直接在脚本中从PyPi安装软件包。也许有一些模块或distutilsdistributepip等)功能使我可以执行类似的操作,pypi.install('requests')并且请求将被安装到我的virtualenv中。

I need to install a package from PyPi straight within my script. Maybe there’s 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.


回答 0

从脚本安装软件包的官方推荐方法是通过子进程调用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])

回答 1

您还可以使用类似:

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')

回答 2

如果要用于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.


回答 3

这应该工作:

import subprocess

def install(name):
    subprocess.call(['pip', 'install', name])

This should work:

import subprocess

def install(name):
    subprocess.call(['pip', 'install', name])

回答 4

我在@Aaron的答案中添加了一些异常处理。

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

回答 5

您可以使用“ install_requires”选项在自己程序包的setup.py中定义从属模块。

如果您的软件包需要生成一些控制台脚本,则可以使用“ console_scripts”入口点来生成包装脚本,该脚本将被放置在“ bin”文件夹(例如您的virtualenv环境)中。

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).