繁体   English   中英

通过从 python 文件中引用来安装 requirements.txt 中的软件包

[英]Installing packages present in requirements.txt by referencing it from a python file

我有以下requirements.txt文件:

beautifulsoup4=4.8.2==py37_0
urllib3=1.25.8=py37_0
pyopenssl=19.1.0=py37_0
openssl=1.1.1d=h1de35cc_4
pandas=1.0.1=py37h6c726b0_0
tqdm=4.42.1=py_0

我需要安装所有这些包,或者确保它们是从 python 脚本中安装的。 我怎样才能做到这一点?

一种方法可以是这样的:

import os
import sys
os.system(f'{sys.executable} -m pip install -r requirements.txt') #take care for path of file

正如@sinoroc 所说,子进程可以在调用命令时采取更多控制(和极端情况处理),在文档中也是如此。

文档建议的一个命令是:

subprocess.check_call([sys.executable, '-m', 'pip', 'install', 'my_package'])

这是subprocess.call的包装。

使用以下内容:

import subprocess
import sys

command = [
    sys.executable,
    '-m',
    'pip',
    'install',
    '--requirement',
    'requirements.txt',
]

subprocess.check_call(command)

使用sys.executable获取当前正在运行的 Python 解释器的路径并将其与-m pip可执行模块)一起使用以确保 100% 确保Z62AD1C2A46C5298F3E2C9为特定的 3 BA8D 解释器安装 Z62AD1C2A46C9,这一点非常重要。 Indeed calling just pip ( script ) delivers absolutely no guarantee as to what Python interpreter will be called, pip could be associated with any Python interpreter on the system.

此外subprocess.check_call确保如果进程未成功结束(即安装未成功),则会引发错误。

以下建议即使不危险,也是不可靠的:

  • os.system('pip install -r requirements.txt')

参考资料

您可以在与 txt 文件位于同一目录时运行命令pip install -r requirements.txt

或在 python 中使用

import os
os.system ('pip install -r path/to/requirements.txt')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM