Pip 能在安装时安装未在 setup.py 中指定的依赖吗?

22 投票
3 回答
10299 浏览
提问于 2025-04-16 06:52

我希望当用户在GitHub上安装原始软件时,pip也能安装我在GitHub上的一个依赖包。这两个包都不在PyPi上(而且永远不会有)。

用户输入的命令是:

pip -e git+https://github.com/Lewisham/cvsanaly@develop#egg=cvsanaly

这个仓库里有一个 requirements.txt 文件,里面还有一个依赖包在GitHub上:

-e git+https://github.com/Lewisham/repositoryhandler#egg=repositoryhandler

我想要的是一个 单一命令,用户只需输入这个命令,就能安装原始包,同时让pip找到需求文件,然后也安装那个依赖包。

3 个回答

1

这回答了你的问题吗?

setup(name='application-xpto',
  version='1.0',
  author='me,me,me',
  author_email='xpto@mail.com',
  packages=find_packages(),
  include_package_data=True,
  description='web app',
  install_requires=open('app/requirements.txt').readlines(),
  )
13

这是我用来从需求文件生成 install_requiresdependency_links 的一个小脚本。

import os
import re

def which(program):
    """
    Detect whether or not a program is installed.
    Thanks to http://stackoverflow.com/a/377028/70191
    """
    def is_exe(fpath):
        return os.path.exists(fpath) and os.access(fpath, os.X_OK)

    fpath, _ = os.path.split(program)
    if fpath:
        if is_exe(program):
            return program
    else:
        for path in os.environ['PATH'].split(os.pathsep):
            exe_file = os.path.join(path, program)
            if is_exe(exe_file):
                return exe_file

    return None

EDITABLE_REQUIREMENT = re.compile(r'^-e (?P<link>(?P<vcs>git|svn|hg|bzr).+#egg=(?P<package>.+)-(?P<version>\d(?:\.\d)*))$')

install_requires = []
dependency_links = []

for requirement in (l.strip() for l in open('requirements')):
    match = EDITABLE_REQUIREMENT.match(requirement)
    if match:
        assert which(match.group('vcs')) is not None, \
            "VCS '%(vcs)s' must be installed in order to install %(link)s" % match.groupdict()
        install_requires.append("%(package)s==%(version)s" % match.groupdict())
        dependency_links.append(match.group('link'))
    else:
        install_requires.append(requirement)
36

这个回答帮我解决了你提到的同样问题。

看起来setup.py没有简单的方法可以直接使用requirements文件来定义它的依赖关系,但同样的信息可以直接写进setup.py里。

我有一个requirements.txt文件:

PIL
-e git://github.com/gabrielgrant/django-ckeditor.git#egg=django-ckeditor

但是在安装这个requirements.txt里包含的包时,pip会忽略这些依赖。

这个setup.py似乎能强制pip安装依赖(包括我在github上的django-ckeditor版本):

from setuptools import setup

setup(
    name='django-articles',
    ...,
    install_requires=[
        'PIL',
        'django-ckeditor>=0.9.3',
    ],
    dependency_links = [
        'http://github.com/gabrielgrant/django-ckeditor/tarball/master#egg=django-ckeditor-0.9.3',
    ]
)

补充:

这个回答也包含了一些有用的信息。

在"#egg=..."中指定版本是为了确认链接中可用的包的版本。 不过需要注意,如果你总是想依赖最新版本,可以在install_requires、dependency_links和其他包的setup.py中把版本设置为dev

补充:根据下面的评论,使用dev作为版本并不是个好主意。

撰写回答