首页 > 解决方案 > 为什么 pip install 使用的参数有时与 import 使用的参数不同?

问题描述

对于许多 python 库,with 使用的参数与import使用 pip 安装库的参数相同。

例如

pip install numpy
pip install scipy
pip install pandas

相当于

import numpy
import scipy
import pandas

但这种模式似乎并不适用于所有图书馆。例如(在这里找到):

pip install Pillow

需要让这个成功

import PIL

根据第一个示例中的模式,我本来希望pip install PIL安装PIL,但我们使用pip install Pillow. 为什么会这样以及它是如何工作的?

标签: pythonpip

解决方案


基本上,您导入的通常是模块名称。例如,您的包可能在以下层次结构中开发:

MyLib
- __init__.py
- my_script1.py
- my_script2.py

但是,当您将库作为“包”在 中可用时pip,通常您需要准备文件,当人们使用安装您的包setup.py时,该文件将自动运行。pip install

setup.py可以是这样的:

from distutils.core import setup
setup(
  name = 'YOURPACKAGENAME',         # How you named your package folder (MyLib)
  packages = ['YOURPACKAGENAME'],   # Chose the same as "name"
  version = '0.1',      # Start with a small number and increase it with every change you make
  license='MIT',        # Chose a license from here: https://help.github.com/articles/licensing-a-repository
  description = 'TYPE YOUR DESCRIPTION HERE',   # Give a short description about your library
  author = 'YOUR NAME',                   # Type in your name
  author_email = 'your.email@domain.com',      # Type in your E-Mail
  url = 'https://github.com/user/reponame',   # Provide either the link to your github or to your website
  download_url = 'https://github.com/user/reponame/archive/v_01.tar.gz',    # I explain this later on
  keywords = ['SOME', 'MEANINGFULL', 'KEYWORDS'],   # Keywords that define your package best
  install_requires=[            # I get to this in a second
          'validators',
          'beautifulsoup4',
      ],
  classifiers=[
    'Development Status :: 3 - Alpha',      # Chose either "3 - Alpha", "4 - Beta" or "5 - Production/Stable" as the current state of your package
    'Intended Audience :: Developers',      # Define that your audience are developers
    'Topic :: Software Development :: Build Tools',
    'License :: OSI Approved :: MIT License',   # Again, pick a license
    'Programming Language :: Python :: 3',      #Specify which pyhton versions that you want to support
    'Programming Language :: Python :: 3.4',
    'Programming Language :: Python :: 3.5',
    'Programming Language :: Python :: 3.6',
  ],
)

因此,在上面的例子中,安装你的包的人pip应该运行pip install YOURPACKAGENAME. 之后,他们需要import MyLib在代码中运行。

TD; 深度学习:

你导入的是一个模块名,但是你安装pip的是包名,它们可以不同。但通常,我会说我喜欢人们使用相同的名字来避免混淆。

参考: https ://medium.com/@joel.barmettler/how-to-upload-your-python-package-to-pypi-65edc5fe9c56


推荐阅读