标签归档:setup.py

使用Python setuptools的安装后脚本

问题:使用Python setuptools的安装后脚本

是否可以在setuptools setup.py文件中指定安装后的Python脚本文件,以便用户可以运行以下命令:

python setup.py install

在本地项目文件存档上,或

pip install <name>

对于PyPI项目,该脚本将在标准setuptools安装完成时运行吗?我希望执行可以在单个Python脚本文件中编码的安装后任务(例如,向用户传递自定义安装后消息,从其他远程源存储库中提取其他数据文件)。

几年前,我遇到了这个SO答案,它回答了该主题,听起来好像当时的共识是您需要创建一个install子命令。如果仍然是这种情况,是否可以有人提供如何执行此操作的示例,以便用户不必输入第二条命令来运行脚本?

Is it possible to specify a post-install Python script file as part of the setuptools setup.py file so that a user can run the command:

python setup.py install

on a local project file archive, or

pip install <name>

for a PyPI project and the script will be run at the completion of the standard setuptools install? I am looking to perform post-install tasks that can be coded in a single Python script file (e.g. deliver a custom post-install message to the user, pull additional data files from a different remote source repository).

I came across this SO answer from several years ago that addresses the topic and it sounds as though the consensus at that time was that you need to create an install subcommand. If that is still the case, would it be possible for someone to provide an example of how to do this so that it is not necessary for the user to enter a second command to run the script?


回答 0

注意:以下解决方案仅在安装源分发zip或tarball或从源树以可编辑模式安装时有效。从二元轮()安装时将无法使用.whl


此解决方案更加透明:

您将添加一些内容,setup.py并且不需要额外的文件。

另外,您还需要考虑两种不同的后安装方式。一个用于开发/可编辑模式,另一个用于安装模式。

将这两个包含安装后脚本的类添加到setup.py

from setuptools import setup
from setuptools.command.develop import develop
from setuptools.command.install import install


class PostDevelopCommand(develop):
    """Post-installation for development mode."""
    def run(self):
        develop.run(self)
        # PUT YOUR POST-INSTALL SCRIPT HERE or CALL A FUNCTION

class PostInstallCommand(install):
    """Post-installation for installation mode."""
    def run(self):
        install.run(self)
        # PUT YOUR POST-INSTALL SCRIPT HERE or CALL A FUNCTION

cmdclasssetup()函数中插入参数setup.py

setup(
    ...

    cmdclass={
        'develop': PostDevelopCommand,
        'install': PostInstallCommand,
    },

    ...
)

您甚至可以在安装过程中调用shell命令,例如在本示例中进行安装前准备工作:

from setuptools import setup
from setuptools.command.develop import develop
from setuptools.command.install import install
from subprocess import check_call


class PreDevelopCommand(develop):
    """Pre-installation for development mode."""
    def run(self):
        check_call("apt-get install this-package".split())
        develop.run(self)

class PreInstallCommand(install):
    """Pre-installation for installation mode."""
    def run(self):
        check_call("apt-get install this-package".split())
        install.run(self)


setup(
    ...

PS:setuptools上没有任何预安装入口点。如果您想知道为什么没有,请阅读此讨论

Note: The solution below only works when installing a source distribution zip or tarball, or installing in editable mode from a source tree. It will not work when installing from a binary wheel (.whl)


This solution is more transparent:

You will make a few additions to setup.py and there is no need for an extra file.

Also you need to consider two different post-installations; one for development/editable mode and the other one for install mode.

Add these two classes that includes your post-install script to setup.py:

from setuptools import setup
from setuptools.command.develop import develop
from setuptools.command.install import install


class PostDevelopCommand(develop):
    """Post-installation for development mode."""
    def run(self):
        develop.run(self)
        # PUT YOUR POST-INSTALL SCRIPT HERE or CALL A FUNCTION

class PostInstallCommand(install):
    """Post-installation for installation mode."""
    def run(self):
        install.run(self)
        # PUT YOUR POST-INSTALL SCRIPT HERE or CALL A FUNCTION

and insert cmdclass argument to setup() function in setup.py:

setup(
    ...

    cmdclass={
        'develop': PostDevelopCommand,
        'install': PostInstallCommand,
    },

    ...
)

You can even call shell commands during installation, like in this example which does pre-installation preparation:

from setuptools import setup
from setuptools.command.develop import develop
from setuptools.command.install import install
from subprocess import check_call


class PreDevelopCommand(develop):
    """Pre-installation for development mode."""
    def run(self):
        check_call("apt-get install this-package".split())
        develop.run(self)

class PreInstallCommand(install):
    """Pre-installation for installation mode."""
    def run(self):
        check_call("apt-get install this-package".split())
        install.run(self)


setup(
    ...

P.S. there are no any pre-install entry points available on setuptools. Read this discussion if you are wondering why there is none.


回答 1

注意:以下解决方案仅在安装源分发zip或tarball或从源树以可编辑模式安装时有效。从二元轮()安装时将无法使用.whl


当安装后脚本要求已安装软件包依赖项时,这是对我有用的唯一策略:

import atexit
from setuptools.command.install import install


def _post_install():
    print('POST INSTALL')


class new_install(install):
    def __init__(self, *args, **kwargs):
        super(new_install, self).__init__(*args, **kwargs)
        atexit.register(_post_install)


setuptools.setup(
    cmdclass={'install': new_install},

Note: The solution below only works when installing a source distribution zip or tarball, or installing in editable mode from a source tree. It will not work when installing from a binary wheel (.whl)


This is the only strategy that has worked for me when the post-install script requires that the package dependencies have already been installed:

import atexit
from setuptools.command.install import install


def _post_install():
    print('POST INSTALL')


class new_install(install):
    def __init__(self, *args, **kwargs):
        super(new_install, self).__init__(*args, **kwargs)
        atexit.register(_post_install)


setuptools.setup(
    cmdclass={'install': new_install},

回答 2

注意:以下解决方案仅在安装源分发zip或tarball或从源树以可编辑模式安装时有效。从二元轮()安装时将无法使用.whl


一个解决方案可能是post_setup.py在in setup.py目录中包含一个。post_setup.py将包含执行安装后功能的功能,并且setup.py只会在适当的时间导入并启动它。

setup.py

from distutils.core import setup
from distutils.command.install_data import install_data

try:
    from post_setup import main as post_install
except ImportError:
    post_install = lambda: None

class my_install(install_data):
    def run(self):
        install_data.run(self)
        post_install()

if __name__ == '__main__':
    setup(
        ...
        cmdclass={'install_data': my_install},
        ...
    )

post_setup.py

def main():
    """Do here your post-install"""
    pass

if __name__ == '__main__':
    main()

通过setup.py从其目录启动的一般想法,您将能够导入,post_setup.py否则它将启动一个空函数。

在中post_setup.py,该if __name__ == '__main__':语句允许您从命令行手动启动安装后。

Note: The solution below only works when installing a source distribution zip or tarball, or installing in editable mode from a source tree. It will not work when installing from a binary wheel (.whl)


A solution could be to include a post_setup.py in setup.py‘s directory. post_setup.py will contain a function which does the post-install and setup.py will only import and launch it at the appropriate time.

In setup.py:

from distutils.core import setup
from distutils.command.install_data import install_data

try:
    from post_setup import main as post_install
except ImportError:
    post_install = lambda: None

class my_install(install_data):
    def run(self):
        install_data.run(self)
        post_install()

if __name__ == '__main__':
    setup(
        ...
        cmdclass={'install_data': my_install},
        ...
    )

In post_setup.py:

def main():
    """Do here your post-install"""
    pass

if __name__ == '__main__':
    main()

With the common idea of launching setup.py from its directory, you will be able to import post_setup.py else it will launch an empty function.

In post_setup.py, the if __name__ == '__main__': statement allows you to manually launch post-install from command line.


回答 3

结合@ Apalala,@ Zulu和@mertyildiran的答案;这在Python 3.5环境中对我有用:

import atexit
import os
import sys
from setuptools import setup
from setuptools.command.install import install

class CustomInstall(install):
    def run(self):
        def _post_install():
            def find_module_path():
                for p in sys.path:
                    if os.path.isdir(p) and my_name in os.listdir(p):
                        return os.path.join(p, my_name)
            install_path = find_module_path()

            # Add your post install code here

        atexit.register(_post_install)
        install.run(self)

setup(
    cmdclass={'install': CustomInstall},
...

这也使您可以访问中的软件包的安装路径install_path,以进行一些shell工作。

Combining the answers from @Apalala, @Zulu and @mertyildiran; this worked for me in a Python 3.5 environment:

import atexit
import os
import sys
from setuptools import setup
from setuptools.command.install import install

class CustomInstall(install):
    def run(self):
        def _post_install():
            def find_module_path():
                for p in sys.path:
                    if os.path.isdir(p) and my_name in os.listdir(p):
                        return os.path.join(p, my_name)
            install_path = find_module_path()

            # Add your post install code here

        atexit.register(_post_install)
        install.run(self)

setup(
    cmdclass={'install': CustomInstall},
...

This also gives you access the to the installation path of the package in install_path, to do some shell work on.


回答 4

我认为执行后安装并保持要求的最简单方法是装饰对的调用setup(...)

from setup tools import setup


def _post_install(setup):
    def _post_actions():
        do_things()
    _post_actions()
    return setup

setup = _post_install(
    setup(
        name='NAME',
        install_requires=['...
    )
)

这将setup()在声明时运行setup。完成需求安装后,它将运行该_post_install()功能,该功能将运行内部功能_post_actions()

I think the easiest way to perform the post-install, and keep the requirements, is to decorate the call to setup(...):

from setup tools import setup


def _post_install(setup):
    def _post_actions():
        do_things()
    _post_actions()
    return setup

setup = _post_install(
    setup(
        name='NAME',
        install_requires=['...
    )
)

This will run setup() when declaring setup. Once done with the requirements installation, it will run the _post_install() function, which will run the inner function _post_actions().


回答 5

如果使用atexit,则无需创建新的cmdclass。您可以直接在setup()调用之前创建atexit寄存器。它做同样的事情。

另外,如果你需要依赖先安装,但这不是用PIP工作进行安装,因为你的atexit处理程序之前PIP移动套餐到位调用。

If using atexit, there is no need to create a new cmdclass. You can simply create your atexit register right before the setup() call. It does the same thing.

Also, if you need dependencies to be installed first, this does not work with pip install since your atexit handler will be called before pip moves the packages into place.


回答 6

我无法通过提出的任何建议来解决问题,因此这对我有所帮助。

你可以调用功能,你想刚过安装之后运行setup()setup.py,这样的:

from setuptools import setup

def _post_install():
    <your code>

setup(...)

_post_install()

I wasn’t able to solve a problem with any presented recommendations, so here is what helped me.

You can call function, that you want to run after installation just after setup() in setup.py, like that:

from setuptools import setup

def _post_install():
    <your code>

setup(...)

_post_install()

requirements.txt与setup.py

问题:requirements.txt与setup.py

我开始使用Python。我已经添加了requirements.txtsetup.py我的项目。但是,我仍然对两个文件的目的感到困惑。我读过,它setup.py是为可再发行的事物而requirements.txt设计的,并且是为不可再发行的事物而设计的。但是我不确定这是正确的。

如何真正使用这两个文件?

I started working with Python. I’ve added requirements.txt and setup.py to my project. But, I am still confused about the purpose of both files. I have read that setup.py is designed for redistributable things and that requirements.txt is designed for non-redistributable things. But I am not certain this is accurate.

How are those two files truly intended to be used?


回答 0

requirements.txt

这可以帮助您设置开发环境。诸如此类的程序pip可用于一次安装文件中列出的所有软件包。之后,您可以开始开发python脚本。如果您计划让其他人参与开发或使用虚拟环境,则特别有用。这是您的用法:

pip install -r requirements.txt

setup.py

这使您可以创建可以重新分发的软件包。该脚本旨在将软件包安装在最终用户的系统上,而不是像在准备开发环境那样pip install -r requirements.txt。有关setup.py的更多详细信息,请参见此答案

两个文件中都列出了项目的依赖项。

requirements.txt:

This helps you to set up your development environment.

Programs like pip can be used to install all packages listed in the file in one fell swoop. After that you can start developing your python script. Especially useful if you plan to have others contribute to the development or use virtual environments. This is how you use it:

pip install -r requirements.txt

setup.py:

This helps you to create packages that you can redistribute.

The setup.py script is meant to install your package on the end user’s system, not to prepare the development environment as pip install -r requirements.txt does. See this answer for more details on setup.py.


The dependencies of your project are listed in both files.


回答 1

简短的答案是requirements.txt仅列出软件包要求。setup.py另一方面更像是一个安装脚本。如果您不打算安装python代码,通常只需要requirements.txt

该文件setup.py除了描述软件包的依赖关系之外,还描述了应打包(或编译,对于本机模块(即,用C编写)的文件和模块)和添加到python软件包列表中的元数据(例如,程序包名称,程序包版本,程序包描述,作者等)。

因为两个文件都列出了依赖性,所以这可能会导致一些重复。请阅读下面的详细信息。

requirements.txt


该文件列出了python软件包的要求。这是一个纯文本文件(可选带注释),列出了python项目的程序包依赖项(每行一个)。它没有描述python软件包的安装方式。通常,您将使用消耗需求文件pip install -r requirements.txt

文本文件的文件名是任意的,但通常requirements.txt是约定的。浏览其他python软件包的源代码存储库时,您可能会偶然发现其他名称,例如dev-dependencies.txtdependencies-dev.txt。它们具有与特定目的相同的目的,dependencies.txt但通常列出特定软件包开发人员感兴趣的其他依赖项,即在发布之前测试源代码(例如pytest,pylint等)。程序包的用户通常不需要整个开发人员依赖项来运行程序包。

如果requirements-X.txt存在多个变体,则通常一个将列出运行时依赖性,而另一个将列出运行时依赖性或测试依赖性。一些项目还会层叠其需求文件,即一个需求文件包含另一个文件时(例如)。这样做可以减少重复。

setup.py


这是一个python脚本,使用该setuptools模块定义python包(名称,包含的文件,包元数据和安装)。像一样requirements.txt,它将列出软件包的运行时依赖项。Setuptools是构建和安装python软件包的实际方法,但是它也有缺点,随着时间的流逝,它催生了新的“元软件包管理器”(如pip)的开发。setuptools的示例缺点是无法安装同一软件包的多个版本,并且缺少卸载命令。

当python用户这样做pip install ./pkgdir_my_module(或pip install my-module)时,pip将setup.py在给定目录(或模块)中运行。同样,setup.py可以pip安装任何具有的模块,例如,pip install .从同一文件夹运行。

我真的需要两者吗?


简短的答案是没有,但同时拥有它们是很好的。它们实现了不同的目的,但是都可以用来列出您的依赖项。

您可能需要考虑一种技巧,以避免在requirements.txt和之间复制依赖项列表setup.py。如果您已经setup.py为您的程序包编写了一个完整的文档,并且您的依赖关系大部分是外部的,则可以考虑requirements.txt仅使用以下内容:

 # requirements.txt
 #
 # installs dependencies from ./setup.py, and the package itself,
 # in editable mode
 -e .

 # (the -e above is optional). you could also just install the package
 # normally with just the line below (after uncommenting)
 # .

-e是一个特殊pip install选项,它以可编辑模式安装给定的软件包。如果pip -r requirements.txt是在这个文件运行时,PIP将通过在列表中安装您的依赖./setup.py。可编辑选项将在您的安装目录中放置一个符号链接(而不是egg或存档副本)。它允许开发人员从存储库中就地编辑代码,而无需重新安装。

当两个文件都位于软件包存储库中时,您还可以利用所谓的“ setuptools extras”。您可以在setup.py中的自定义类别下定义可选软件包,然后使用pip从该类别安装这些软件包:

# setup.py
from setuptools import setup
setup(
   name="FOO"
   ...
   extras_require = {
       'dev': ['pylint'],
       'build': ['requests']
   }
   ...
)

然后在需求文件中:

# install packages in the [build] category, from setup.py
# (path/to/mypkg is the directory where setup.py is)
-e path/to/mypkg[build]

这会将所有依赖项列表保留在setup.py中。

注意:通常,您可以从沙箱中执行pip和setup.py,例如使用program创建的virtualenv。这样可以避免在项目开发环境的上下文之外安装python软件包。

The short answer is that requirements.txt is for listing package requirements only. setup.py on the other hand is more like an installation script. If you don’t plan on installing the python code, typically you would only need requirements.txt.

The file setup.py describes, in addition to the package dependencies, the set of files and modules that should be packaged (or compiled, in the case of native modules (i.e., written in C)), and metadata to add to the python package listings (e.g. package name, package version, package description, author, …).

Because both files list dependencies, this can lead to a bit of duplication. Read below for details.

requirements.txt


This file lists python package requirements. It is a plain text file (optionally with comments) that lists the package dependencies of your python project (one per line). It does not describe the way in which your python package is installed. You would generally consume the requirements file with pip install -r requirements.txt.

The filename of the text file is arbitrary, but is often requirements.txt by convention. When exploring source code repositories of other python packages, you might stumble on other names, such as dev-dependencies.txt or dependencies-dev.txt. Those serve the same purpose as dependencies.txt but generally list additional dependencies of interest to developers of the particular package, namely for testing the source code (e.g. pytest, pylint, etc.) before release. Users of the package generally wouldn’t need the entire set of developer dependencies to run the package.

If multiplerequirements-X.txt variants are present, then usually one will list runtime dependencies, and the other build-time, or test dependencies. Some projects also cascade their requirements file, i.e. when one requirements file includes another file (example). Doing so can reduce repetition.

setup.py


This is a python script which uses the setuptools module to define a python package (name, files included, package metadata, and installation). It will, like requirements.txt, also list runtime dependencies of the package. Setuptools is the de-facto way to build and install python packages, but it has its shortcomings, which over time have sprouted the development of new “meta-package managers”, like pip. Example shortcomings of setuptools are its inability to install multiple versions of the same package, and lack of an uninstall command.

When a python user does pip install ./pkgdir_my_module (or pip install my-module), pip will run setup.py in the given directory (or module). Similarly, any module which has a setup.py can be pip-installed, e.g. by running pip install . from the same folder.

Do I really need both?


Short answer is no, but it’s nice to have both. They achieve different purposes, but they can both be used to list your dependencies.

There is one trick you may consider to avoid duplicating your list of dependencies between requirements.txt and setup.py. If you have written a fully working setup.py for your package already, and your dependencies are mostly external, you could consider having a simple requirements.txt with only the following:

 # requirements.txt
 #
 # installs dependencies from ./setup.py, and the package itself,
 # in editable mode
 -e .

 # (the -e above is optional). you could also just install the package
 # normally with just the line below (after uncommenting)
 # .

The -e is a special pip install option which installs the given package in editable mode. When pip -r requirements.txt is run on this file, pip will install your dependencies via the list in ./setup.py. The editable option will place a symlink in your install directory (instead of an egg or archived copy). It allows developers to edit code in place from the repository without reinstalling.

You can also take advantage of what’s called “setuptools extras” when you have both files in your package repository. You can define optional packages in setup.py under a custom category, and install those packages from just that category with pip:

# setup.py
from setuptools import setup
setup(
   name="FOO"
   ...
   extras_require = {
       'dev': ['pylint'],
       'build': ['requests']
   }
   ...
)

and then, in the requirements file:

# install packages in the [build] category, from setup.py
# (path/to/mypkg is the directory where setup.py is)
-e path/to/mypkg[build]

This would keep all your dependency lists inside setup.py.

Note: You would normally execute pip and setup.py from a sandbox, such as those created with the program virtualenv. This will avoid installing python packages outside the context of your project’s development environment.


回答 2

为了完整起见,以下是我从3 4个不同角度看待它的方法。

  1. 他们的设计目的是不同的

这是官方文档(重点是我的)中引用的精确描述:

尽管install_requires(在setup.py中)定义了单个项目的依赖关系,但“需求文件”通常用于定义完整Python环境的需求。

尽管install_requires需求最少,但是需求文件通常包含固定版本的详尽列表,目的是实现完整环境的可重复安装。

但是它可能仍然不容易理解,因此在下一节中,将提供2个事实示例,以不同的方式演示应如何使用这两种方法。

  1. 因此,它们的实际用法(应该是)不同

    • 如果您的项目foo将作为独立的库发布(意味着其他人可能会这样做import foo),那么您(和下游用户)将希望有一个灵活的依赖声明,以使您的库不会(而且一定不能) )对您的依赖项的确切版本“保持警惕”。因此,通常,您的setup.py将包含以下行:

      install_requires=[
          'A>=1,<2',
          'B>=2'
      ]
    • 如果您只是想以某种方式为您的应用程序“记录”或“固定”您的EXACT当前环境bar,这意味着您或您的用户希望bar按原样使用您的应用程序,即运行python bar.py,您可能希望冻结您的环境,以便它总是表现相同。在这种情况下,您的需求文件将如下所示:

      A==1.2.3
      B==2.3.4
      # It could even contain some dependencies NOT strickly required by your library
      pylint==3.4.5
  2. 实际上,我该使用哪一个?

    • 如果您正在开发bar将由所使用的应用程序python bar.py,即使该应用程序只是“有趣的脚本”,仍然建议您使用requirements.txt,因为谁知道下周(恰好是圣诞节)您会收到新计算机作为礼物,因此您需要在此重新设置您的确切环境。

    • 如果您正在开发foo将由所使用的库,则必须import foo准备setup.py。期。但是您仍然可以选择同时提供require.txt,它可以:

      (a)采用任何一种A==1.2.3风格(如上文第2条所述);

      (b)或只包含一个魔法单曲 .

      .

      大致等于“基于setup.py安装要求”,而无需重复。我个人认为这是最后一种方法,模糊了界限,增加了混乱,并没有真正增加价值,但这仍然是Python包装维护商Donald在他的博客文章中提到的一种方法。

  3. 下限不同。

    即使遵循了以上3条条件,并正确地决定了您的库hybrid-engine仍将使用a setup.py声明其依赖关系engine>=1.2.0,而示例应用程序reliable-car仍将使用requirements.txt其声明其依赖关系engine>=1.2.3,即使最新版本的engine1.4.0也是如此。如您所见,您对它们的下限数字的选择仍然略有不同。这就是为什么。

    • hybrid-engineengine>=1.2.0假设是因为,假设地,首先引入了所需的“内部燃烧”功能engine 1.2.0,而该功能是必不可少的hybrid-engine,而不管该版本内部是否存在某些(较小的)错误,并已在后续版本1.2.1中进行了修复。 ,1.2.2和1.2.3。

    • reliable-car取决于,engine>=1.2.3因为到目前为止,这是没有已知问题的最早版本。当然,以后的版本中会有新功能,例如引入了“电动机”和引入了engine 1.3.0“核反应堆” engine 1.4.0,但是对于项目而言,它们并不是必需的reliable-car

For the sake of completeness, here is how I see it in 3 4 different angles.

  1. Their design purposes are different

This is the precise description quoted from the official documentation (emphasis mine):

Whereas install_requires (in setup.py) defines the dependencies for a single project, Requirements Files are often used to define the requirements for a complete Python environment.

Whereas install_requires requirements are minimal, requirements files often contain an exhaustive listing of pinned versions for the purpose of achieving repeatable installations of a complete environment.

But it might still not easy to be understood, so in next section, there come 2 factual examples to demonstrate how the 2 approaches are supposed to be used, differently.

  1. Their actual usages are therefore (supposed to be) different

    • If your project foo is going to be released as a standalone library (meaning, others would probably do import foo), then you (and your downstream users) would want to have a flexible declaration of dependency, so that your library would not (and it must not) be “picky” about what exact version of YOUR dependencies should be. So, typically, your setup.py would contain lines like this:

      install_requires=[
          'A>=1,<2',
          'B>=2'
      ]
      
    • If you just want to somehow “document” or “pin” your EXACT current environment for your application bar, meaning, you or your users would like to use your application bar as-is, i.e. running python bar.py, you may want to freeze your environment so that it would always behave the same. In such case, your requirements file would look like this:

      A==1.2.3
      B==2.3.4
      # It could even contain some dependencies NOT strickly required by your library
      pylint==3.4.5
      
  2. In reality, which one do I use?

    • If you are developing an application bar which will be used by python bar.py, even if that is “just script for fun”, you are still recommended to use requirements.txt because, who knows, next week (which happens to be Christmas) you would receive a new computer as a gift, so you would need to setup your exact environment there again.

    • If you are developing a library foo which will be used by import foo, you have to prepare a setup.py. Period. But you may still choose to also provide a requirements.txt at the same time, which can:

      (a) either be in the A==1.2.3 style (as explained in #2 above);

      (b) or just contain a magical single .

      .
      

      which would roughly equal to “install the requirements based on setup.py” while without duplication. Personally I consider this last approach kind of blurs the line, adds to the confusion and does NOT really add value, but it is nonetheless a trick derived from an approach mentioned by Python packaging maintainer Donald in his blog post.

  3. Different lower bounds.

    Even after you have followed the above 3 criteria and correctly decided that your library hybrid-engine would use a setup.py to declare its dependency engine>=1.2.0, and your sample application reliable-car would use requirements.txt to declare its dependency engine>=1.2.3, even though the latest version of engine is already at 1.4.0. As you see, your choice for their lower bound number are still subtly different. And here is why.

    • hybrid-engine depends on engine>=1.2.0 because, hypothetically speaking, the needed “internal combustion” capability was first introduced in engine 1.2.0, and that capability is the necessity of hybrid-engine, regardless of whether there might be some (minor) bugs inside such version and been fixed in subsequent versions 1.2.1, 1.2.2, and 1.2.3.

    • reliable-car depends on engine>=1.2.3 because that is the earliest version WITHOUT known issues, so far. Sure there are new capabilities in later versions, say, “electric motor” introduced in engine 1.3.0, and “nuclear reactor” introduced in engine 1.4.0, but they are not necessary for project reliable-car.


‘python setup.py install’和’pip install’之间的区别

问题:’python setup.py install’和’pip install’之间的区别

我有一个要从tar文件安装到python virtualenv中的外部软件包。安装软件包的最佳方法是什么?

我发现了两种方法可以做到这一点:

  1. 提取tar文件,然后python setup.py install在提取的目录中运行。
  2. pip install packagename.tar.gz来自https://pip.pypa.io/en/stable/reference/pip_install/#examples中的示例7

这两种方式在做上是否有区别。

I have an external package I want to install into my python virtualenv from a tar file. What is the best way to install the package?

I’ve discovered 2 ways that can do it:

  1. Extract the tar file, then run python setup.py install inside of the extracted directory.
  2. pip install packagename.tar.gz from example # 7 in https://pip.pypa.io/en/stable/reference/pip_install/#examples

Is if there is any difference doing them in these 2 ways.


回答 0

从表面上看,都做同样的事情:无论是做python setup.py install还是pip install <PACKAGE-NAME>会安装Python包的你,有大惊小怪的最低金额。

但是,使用pip具有一些其他优点,使其更易于使用。

  • pip将自动为您下载软件包的所有依赖项。相反,如果使用setup.py,则通常必须手动搜索并下载依赖项,这很乏味并且会令人沮丧。
  • pip跟踪各种元数据,使您可以使用一个命令轻松卸载和更新软件包:pip uninstall <PACKAGE-NAME>pip install --upgrade <PACKAGE-NAME>。相反,如果您使用setup.py,则要想摆脱它,必须手动手动删除和维护该软件包,这可能容易出错。
  • 您不再需要手动下载文件。如果您使用setup.py,则必须访问图书馆的网站,弄清楚从哪里下载,提取文件,运行setup.py…相比之下,pip会自动搜索Python软件包索引(PyPi)来查看该软件包是否存在,以及会自动为您下载,解压缩并安装该软件包。除了少数exceptions,几乎所有真正有用的Python库都可以在PyPi上找到。
  • pip可让您轻松安装轮子,这是Python发行版的新标准。有关轮子的更多信息
  • pip提供了与using良好集成的其他好处virtualenv,该程序使您可以运行多个项目,这些项目需要计算机上具有冲突的库和Python版本。更多信息
  • pip默认情况下与Python 2.x系列的Python 2.7.9及Python 3.x系列的Python 3.4.0及更高版本捆绑在一起,从而更加易于使用。

因此,基本上,使用点子。它仅提供对的改进python setup.py install


如果您使用的是旧版本的Python,无法升级且未安装pip,则可以在以下链接中找到有关安装pip的更多信息:

pip本身并不需要教程。90%的时间,您真正需要的唯一命令是pip install <PACKAGE-NAME>。就是说,如果您想了解更多有关pip的功能的详细信息,请参阅:

通常也建议同时使用pip和virtualenv。如果您是Python的初学者,我个人认为最好只使用pip并在全球范围内安装软件包,但最终我还是认为在处理更严重的项目时,您应该过渡到使用virtualenv。

如果您想了解有关一起使用pip和virtualenv的更多信息,请参见:

On the surface, both do the same thing: doing either python setup.py install or pip install <PACKAGE-NAME> will install your python package for you, with a minimum amount of fuss.

However, using pip offers some additional advantages that make it much nicer to use.

  • pip will automatically download all dependencies for a package for you. In contrast, if you use setup.py, you often have to manually search out and download dependencies, which is tedious and can become frustrating.
  • pip keeps track of various metadata that lets you easily uninstall and update packages with a single command: pip uninstall <PACKAGE-NAME> and pip install --upgrade <PACKAGE-NAME>. In contrast, if you install a package using setup.py, you have to manually delete and maintain a package by hand if you want to get rid of it, which could be potentially error-prone.
  • You no longer have to manually download your files. If you use setup.py, you have to visit the library’s website, figure out where to download it, extract the file, run setup.py… In contrast, pip will automatically search the Python Package Index (PyPi) to see if the package exists there, and will automatically download, extract, and install the package for you. With a few exceptions, almost every single genuinely useful Python library can be found on PyPi.
  • pip will let you easily install wheels, which is the new standard of Python distribution. More info about wheels.
  • pip offers additional benefits that integrate well with using virtualenv, which is a program that lets you run multiple projects that require conflicting libraries and Python versions on your computer. More info.
  • pip is bundled by default with Python as of Python 2.7.9 on the Python 2.x series, and as of Python 3.4.0 on the Python 3.x series, making it even easier to use.

So basically, use pip. It only offers improvements over using python setup.py install.


If you’re using an older version of Python, can’t upgrade, and don’t have pip installed, you can find more information about installing pip at the following links:

pip, by itself, doesn’t really require a tutorial. 90% of the time, the only command you really need is pip install <PACKAGE-NAME>. That said, if you’re interested in learning more about the details of what exactly you can do with pip, see:

It is also commonly recommended that you use pip and virtualenv together. If you’re a beginner to Python, I personally think it’d be fine to start of with just using pip and install packages globally, but eventually I do think you should transition to using virtualenv as you tackle more serious projects.

If you’d like to learn more about using pip and virtualenv together, see:


回答 1

python setup.py install与make install类似:这是将文件编译和复制到目标目录的有限方式。这并不意味着它是在系统上真正安装软件的最佳方法。

pip是一个程序包管理器,可以安装,升级,列出和卸载程序包,例如熟悉的程序包管理器,包括:dpkg, apt, yum, urpmi, ports等。它可以在内运行python setup.py install,但具有特定的选项来控制最终安装的方式和位置。

总结:使用pip

python setup.py install is the analog of make install: it’s a limited way to compile and copy files to destination directories. This doesn’t mean that it’s the best way to really install software on your system.

pip is a package manager, which can install, upgrade, list and uninstall packages, like familiar package managers including: dpkg, apt, yum, urpmi, ports etc. Under the hood, it will run python setup.py install, but with specific options to control how and where things end up installed.

In summary: use pip.


回答 2

问题是关于安装包含python软件包而不是NOT 的本地tarball的首选方法关于将软件包上传到索引服务(如PyPi)的好处。

至少我知道一些软件发行商不会将其软件包上传到PyPi,而是要求开发人员从其网站下载软件包并进行安装。

python setup.py安装

这可以工作,但不建议这样做。无需解压缩tarball文件并进入其中以运行setup.py文件。

点安装../path/to/packagename.tar.gz

这是设计和首选的方式。简洁并与PyPi样式的包对齐。

有关更多信息,请pip install参见:https//pip.readthedocs.io/en/stable/reference/pip_install/

The question is about the preferred method to install a local tarball containing a python package, NOT about the advantage of uploading package to an indexing service like PyPi.

As lest I know some software distributor does not upload their package to PyPi, instead asking developers to download package from their website and install.

python setup.py install

This can work but not recommended. It’s not necessary to unwrap the tarball file and go into it to run setup.py file.

pip install ../path/to/packagename.tar.gz

This is the way designed and preferred. Concise and align with PyPi-style packages.

More information about pip install can be found here: https://pip.readthedocs.io/en/stable/reference/pip_install/


没有名为setuptools的模块

问题:没有名为setuptools的模块

我想安装twilio的安装文件。通过给定命令安装它时,出现错误:

没有名为setuptools的模块。

您能告诉我该怎么办吗?

我在用 python 2.7

Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.

C:\Python27>python D:\test\twilio-twilio-python-26f6707\setup.py install
Traceback (most recent call last):
  File "D:\test\twilio-twilio-python-26f6707\setup.py", line 2, in <module>
    from setuptools import setup, find_packages
ImportError: No module named setuptools

I want to install setup file of twilio. When I install it through given command it is given me an error:

No module named setuptools.

Could you please let me know what should I do?

I am using python 2.7

Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.

C:\Python27>python D:\test\twilio-twilio-python-26f6707\setup.py install
Traceback (most recent call last):
  File "D:\test\twilio-twilio-python-26f6707\setup.py", line 2, in <module>
    from setuptools import setup, find_packages
ImportError: No module named setuptools

回答 0

安装并重setuptools试。

尝试命令:

sudo apt-get install -y python-setuptools

Install setuptools and try again.

try command:

sudo apt-get install -y python-setuptools

回答 1

对于ubuntu用户,由于未在系统范围内安装setuptool,因此可能会出现此错误。只需使用以下命令安装setuptool:

sudo apt-get install -y python-setuptools

对于python3:

sudo apt-get install -y python3-setuptools

之后,请使用

sudo python setup.py install

就这样。

For ubuntu users, this error may arise because setuptool is not installed system-wide. Simply install setuptool using the command:

sudo apt-get install -y python-setuptools

For python3:

sudo apt-get install -y python3-setuptools

After that, install your package again normally, using

sudo python setup.py install

That’s all.


回答 2

对于Python运行此命令

apt-get install -y python-setuptools

对于Python 3。

apt-get install -y python3-setuptools

For Python Run This Command

apt-get install -y python-setuptools

For Python 3.

apt-get install -y python3-setuptools

回答 3

PyPA推荐的用于安装和管理Python包的工具pippip包含在Python 3.4(PEP 453)中,但是对于较旧的版本,这是安装方法(在Windows上使用Python 3.3):

下载https://bootstrap.pypa.io/get-pip.py

>c:\Python33\python.exe get-pip.py
Downloading/unpacking pip
Downloading/unpacking setuptools
Installing collected packages: pip, setuptools
Successfully installed pip setuptools
Cleaning up...

用法示例:

>c:\Python33\Scripts\pip.exe install pymysql
Downloading/unpacking pymysql
Installing collected packages: pymysql
Successfully installed pymysql
Cleaning up...

在您的情况下,将是这样(似乎pip缓存独立于Python版本):

C:\Python27>python.exe \code\Python\get-pip.py
Requirement already up-to-date: pip in c:\python27\lib\site-packages
Collecting wheel
  Downloading wheel-0.29.0-py2.py3-none-any.whl (66kB)
    100% |################################| 69kB 255kB/s
Installing collected packages: wheel
Successfully installed wheel-0.29.0

C:\Python27>cd Scripts

C:\Python27\Scripts>pip install twilio
Collecting twilio
  Using cached twilio-5.3.0.tar.gz
Collecting httplib2>=0.7 (from twilio)
  Using cached httplib2-0.9.2.tar.gz
Collecting six (from twilio)
  Using cached six-1.10.0-py2.py3-none-any.whl
Collecting pytz (from twilio)
  Using cached pytz-2015.7-py2.py3-none-any.whl
Building wheels for collected packages: twilio, httplib2
  Running setup.py bdist_wheel for twilio ... done
  Stored in directory: C:\Users\Cees.Timmerman\AppData\Local\pip\Cache\wheels\e0\f2\a7\c57f6d153c440b93bd24c1243123f276dcacbf43cc43b7f906
  Running setup.py bdist_wheel for httplib2 ... done
  Stored in directory: C:\Users\Cees.Timmerman\AppData\Local\pip\Cache\wheels\e1\a3\05\e66aad1380335ee0a823c8f1b9006efa577236a24b3cb1eade
Successfully built twilio httplib2
Installing collected packages: httplib2, six, pytz, twilio
Successfully installed httplib2-0.9.2 pytz-2015.7 six-1.10.0 twilio-5.3.0

The PyPA recommended tool for installing and managing Python packages is pip. pip is included with Python 3.4 (PEP 453), but for older versions here’s how to install it (on Windows, using Python 3.3):

Download https://bootstrap.pypa.io/get-pip.py

>c:\Python33\python.exe get-pip.py
Downloading/unpacking pip
Downloading/unpacking setuptools
Installing collected packages: pip, setuptools
Successfully installed pip setuptools
Cleaning up...

Sample usage:

>c:\Python33\Scripts\pip.exe install pymysql
Downloading/unpacking pymysql
Installing collected packages: pymysql
Successfully installed pymysql
Cleaning up...

In your case it would be this (it appears that pip caches independent of Python version):

C:\Python27>python.exe \code\Python\get-pip.py
Requirement already up-to-date: pip in c:\python27\lib\site-packages
Collecting wheel
  Downloading wheel-0.29.0-py2.py3-none-any.whl (66kB)
    100% |################################| 69kB 255kB/s
Installing collected packages: wheel
Successfully installed wheel-0.29.0

C:\Python27>cd Scripts

C:\Python27\Scripts>pip install twilio
Collecting twilio
  Using cached twilio-5.3.0.tar.gz
Collecting httplib2>=0.7 (from twilio)
  Using cached httplib2-0.9.2.tar.gz
Collecting six (from twilio)
  Using cached six-1.10.0-py2.py3-none-any.whl
Collecting pytz (from twilio)
  Using cached pytz-2015.7-py2.py3-none-any.whl
Building wheels for collected packages: twilio, httplib2
  Running setup.py bdist_wheel for twilio ... done
  Stored in directory: C:\Users\Cees.Timmerman\AppData\Local\pip\Cache\wheels\e0\f2\a7\c57f6d153c440b93bd24c1243123f276dcacbf43cc43b7f906
  Running setup.py bdist_wheel for httplib2 ... done
  Stored in directory: C:\Users\Cees.Timmerman\AppData\Local\pip\Cache\wheels\e1\a3\05\e66aad1380335ee0a823c8f1b9006efa577236a24b3cb1eade
Successfully built twilio httplib2
Installing collected packages: httplib2, six, pytz, twilio
Successfully installed httplib2-0.9.2 pytz-2015.7 six-1.10.0 twilio-5.3.0

回答 4

对于python3是:

sudo apt-get install -y python3-setuptools

For python3 is:

sudo apt-get install -y python3-setuptools

Python 3:ImportError“没有名为Setuptools的模块”

问题:Python 3:ImportError“没有名为Setuptools的模块”

我在使用Python 3安装软件包时遇到了麻烦。

我一直都使用来安装软件包setup.py install。但是现在,当我尝试安装ansicolors软件包时,我得到了:

importerror“没有名为Setuptools的模块”

我不知道该怎么办,因为过去我没有安装过setuptools。尽管如此,我仍然能够在setup.py install没有setuptools的情况下安装许多软件包。为什么现在应该获得setuptools?

我什至无法安装setuptools,因为我有Python 3.3,setuptools不支持Python 3。

为什么我的安装命令不再起作用?

I’m having troubles with installing packages in Python 3.

I have always installed packages with setup.py install. But now, when I try to install the ansicolors package I get:

importerror “No Module named Setuptools”

I have no idea what to do because I didn’t have setuptools installed in the past. Still, I was able to install many packages with setup.py install without setuptools. Why should I get setuptools now?

I can’t even install setuptools because I have Python 3.3 and setuptools doesn’t support Python 3.

Why doesn’t my install command work anymore?


回答 0

您的setup.py文件需要setuptools。一些Python软件包曾经distutils用于分发,但现在大多数都使用setuptools了一个更完整的软件包。是有关它们之间差异的问题。

setuptools在Debian上安装:

sudo apt-get install python3-setuptools

对于旧版本的Python(Python 2.x):

sudo apt-get install python-setuptools

Your setup.py file needs setuptools. Some Python packages used to use distutils for distribution, but most now use setuptools, a more complete package. Here is a question about the differences between them.

To install setuptools on Debian:

sudo apt-get install python3-setuptools

For an older version of Python (Python 2.x):

sudo apt-get install python-setuptools

回答 1

编辑:官方setuptools dox页面

如果您从python.org安装了Python 2> = 2.7.9或Python 3> = 3.4,则已经具有pip和setuptools,但需要升级到最新版本:

在Linux或OS X上:

pip install -U pip setuptools 

在Windows上:

python -m pip install -U pip setuptools

因此,本文的其余部分可能已过时(例如,某些链接不起作用)。

分发 -是setuptools分支,可“提供Python 3支持”。Distribution(setuptools)+ pip的安装说明:

curl -O http://python-distribute.org/distribute_setup.py
python distribute_setup.py
easy_install pip

这里有类似的问题。

更新:分发似乎已过时,即已合并到Setuptools中:分发是Setuptools项目不推荐使用的分支。从Setuptools 0.7发行版开始,Setuptools和Distribute已合并,并且不再维护Distribute。所有正在进行的工作应参考Setuptools项目和Setuptools文档。

您可以尝试在setuptools pypi页面上找到说明(我尚未对此进行测试,对不起:():

wget https://bitbucket.org/pypa/setuptools/raw/bootstrap/ez_setup.py -O - | python
easy_install pip

EDIT: Official setuptools dox page:

If you have Python 2 >=2.7.9 or Python 3 >=3.4 installed from python.org, you will already have pip and setuptools, but will need to upgrade to the latest version:

On Linux or OS X:

pip install -U pip setuptools 

On Windows:

python -m pip install -U pip setuptools

Therefore the rest of this post is probably obsolete (e.g. some links don’t work).

Distribute – is a setuptools fork which “offers Python 3 support”. Installation instructions for distribute(setuptools) + pip:

curl -O http://python-distribute.org/distribute_setup.py
python distribute_setup.py
easy_install pip

Similar issue here.

UPDATE: Distribute seems to be obsolete, i.e. merged into Setuptools: Distribute is a deprecated fork of the Setuptools project. Since the Setuptools 0.7 release, Setuptools and Distribute have merged and Distribute is no longer being maintained. All ongoing effort should reference the Setuptools project and the Setuptools documentation.

You may try with instructions found on setuptools pypi page (I haven’t tested this, sorry :( ):

wget https://bitbucket.org/pypa/setuptools/raw/bootstrap/ez_setup.py -O - | python
easy_install pip

回答 2

我在使用python-2.6的Oracle Linux 6.4上的virtualenv内执行此操作,因此基于apt的解决方案对我来说不是一个选择,python-2.7的想法也不对。我的解决方法是升级我由virtualenv安装的setuptools版本:

pip install --upgrade setuptools

之后,我能够将软件包安装到virtualenv中。我知道这个问题已经选择了答案,但我希望这个答案对我的情况有所帮助。

I was doing this inside a virtualenv on Oracle Linux 6.4 using python-2.6 so the apt-based solutions weren’t an option for me, nor were the python-2.7 ideas. My fix was to upgrade my version of setuptools that had been installed by virtualenv:

pip install --upgrade setuptools

After that, I was able to install packages into the virtualenv. I know this question has already had an answer selected but I hope this answer will help others in my situation.


回答 3

pip uninstall setuptools

然后:

pip install setuptools

这对我有用,并解决了我的问题。

pip uninstall setuptools

and then:

pip install setuptools

This works for me and fix my issue.


回答 4

distribute软件包提供了与Python 3兼容的版本setuptoolshttp : //pypi.python.org/pypi/distribute

另外,用于pip安装模块。它会自动找到依赖项并为您安装它们。

对于您的包裹,它对我来说效果很好:

[~] pip --version                                                              
pip 1.2.1 from /usr/lib/python3.3/site-packages (python 3.3)
[~] sudo pip install ansicolors                                                
Downloading/unpacking ansicolors
  Downloading ansicolors-1.0.2.tar.gz
  Running setup.py egg_info for package ansicolors

Installing collected packages: ansicolors
  Running setup.py install for ansicolors

Successfully installed ansicolors
Cleaning up...
[~]

The distribute package provides a Python 3-compatible version of setuptools: http://pypi.python.org/pypi/distribute

Also, use pip to install the modules. It automatically finds dependencies and installs them for you.

It works just fine for me with your package:

[~] pip --version                                                              
pip 1.2.1 from /usr/lib/python3.3/site-packages (python 3.3)
[~] sudo pip install ansicolors                                                
Downloading/unpacking ansicolors
  Downloading ansicolors-1.0.2.tar.gz
  Running setup.py egg_info for package ansicolors

Installing collected packages: ansicolors
  Running setup.py install for ansicolors

Successfully installed ansicolors
Cleaning up...
[~]

回答 5

Windows 7的:

我在这里为python selenium webdriver 提供了完整的解决方案

1. Setup easy install (windows - simplified)
    a. download ez.setup.py (https://bootstrap.pypa.io/ez_setup.py) from 'https://pypi.python.org/pypi/setuptools'
    b. move ez.setup.py to C:\Python27\
    c. open cmd prompt
    d. cd C:\Python27\
    e. C:\Python27\python.exe ez.setup.py install

Windows 7:

I have given a complete solution here for python selenium webdriver

1. Setup easy install (windows - simplified)
    a. download ez.setup.py (https://bootstrap.pypa.io/ez_setup.py) from 'https://pypi.python.org/pypi/setuptools'
    b. move ez.setup.py to C:\Python27\
    c. open cmd prompt
    d. cd C:\Python27\
    e. C:\Python27\python.exe ez.setup.py install

回答 6

PyPA推荐的用于安装和管理Python包的工具pippip包括在Python 3.4(PEP 453),但对于旧版本这里是如何安装它(在Windows上):

下载https://bootstrap.pypa.io/get-pip.py

>c:\Python33\python.exe get-pip.py
Downloading/unpacking pip
Downloading/unpacking setuptools
Installing collected packages: pip, setuptools
Successfully installed pip setuptools
Cleaning up...

>c:\Python33\Scripts\pip.exe install pymysql
Downloading/unpacking pymysql
Installing collected packages: pymysql
Successfully installed pymysql
Cleaning up...

The PyPA recommended tool for installing and managing Python packages is pip. pip is included with Python 3.4 (PEP 453), but for older versions here’s how to install it (on Windows):

Download https://bootstrap.pypa.io/get-pip.py

>c:\Python33\python.exe get-pip.py
Downloading/unpacking pip
Downloading/unpacking setuptools
Installing collected packages: pip, setuptools
Successfully installed pip setuptools
Cleaning up...

>c:\Python33\Scripts\pip.exe install pymysql
Downloading/unpacking pymysql
Installing collected packages: pymysql
Successfully installed pymysql
Cleaning up...

回答 7

几年前,我继承了在Django-1.2.3下运行的python(2.7.1)项目,现在被要求使用QR增强功能。遇到了同样的问题,没有找到pip或apt-get。所以我以完全不同但简单的方式解决了它。我/ bin / vi-ed setup.py,并将“ from setuptools import setup”这一行更改为:“ from distutils.core import setup”对我而言,所以我认为我应该将它发布给其他运行旧python的用户。问候,罗杰·维米尔

A few years ago I inherited a python (2.7.1) project running under Django-1.2.3 and now was asked to enhance it with QR possibilities. Got the same problem and did not find pip or apt-get either. So I solved it in a totally different but easy way. I /bin/vi-ed the setup.py and changed the line “from setuptools import setup” into: “from distutils.core import setup” That did it for me, so I thought I should post this for other users running old pythons. Regards, Roger Vermeir


为什么python setup.py在Travis CI上说无效命令’bdist_wheel’?

问题:为什么python setup.py在Travis CI上说无效命令’bdist_wheel’?

我的Python软件包具有一个setup.py在本地配置时可以在Ubuntu Trusty和新的Vagrant Ubuntu Trusty VM上正常运行的软件包:

sudo apt-get install python python-dev --force-yes --assume-yes --fix-broken
curl --silent --show-error --retry 5 https://bootstrap.pypa.io/get-pip.py | sudo python2.7
sudo -H pip install setuptools wheel virtualenv --upgrade

但是,当我在Travis CI Trusty Beta VM上执行相同操作时:

- sudo apt-get install python python-dev --force-yes --assume-yes --fix-broken
- curl --silent --show-error --retry 5 https://bootstrap.pypa.io/get-pip.py | sudo python2.7
- sudo -H pip install setuptools wheel virtualenv --upgrade

我得到:

python2.7 setup.py bdist_wheel
usage: setup.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...]
   or: setup.py --help [cmd1 cmd2 ...]
   or: setup.py --help-commands
   or: setup.py cmd --help
error: invalid command 'bdist_wheel'

为什么我不能在python中创建轮子?是相关的,但请注意,我正在安装滚轮并升级setuptools。

My Python package has a setup.py which builds fine locally on Ubuntu Trusty and on a fresh Vagrant Ubuntu Trusty VM when I provision it like this:

sudo apt-get install python python-dev --force-yes --assume-yes --fix-broken
curl --silent --show-error --retry 5 https://bootstrap.pypa.io/get-pip.py | sudo python2.7
sudo -H pip install setuptools wheel virtualenv --upgrade

But when I do the same on a Travis CI Trusty Beta VM:

- sudo apt-get install python python-dev --force-yes --assume-yes --fix-broken
- curl --silent --show-error --retry 5 https://bootstrap.pypa.io/get-pip.py | sudo python2.7
- sudo -H pip install setuptools wheel virtualenv --upgrade

I get:

python2.7 setup.py bdist_wheel
usage: setup.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...]
   or: setup.py --help [cmd1 cmd2 ...]
   or: setup.py --help-commands
   or: setup.py cmd --help
error: invalid command 'bdist_wheel'

This Why can I not create a wheel in python? is related but note I am installing wheel and upgrading setuptools.


回答 0

不得不安装该wheel软件包。一切都是最新的,但仍然给出错误。

pip install wheel

然后

python setup.py bdist_wheel 

工作没有问题。

Had to install the wheel package. Everything was up to date but still giving the error.

pip install wheel

then

python setup.py bdist_wheel 

Worked without issues.


回答 1

pip install wheel

为我工作,但您也可以添加此内容

setup(
    ...
    setup_requires=['wheel']
)

来setup.py并保存点子安装命令

pip install wheel

worked for me, but you can also add this

setup(
    ...
    setup_requires=['wheel']
)

to setup.py and save yourself a pip install command


回答 2

2020年1月

浪费了2个小时。

在AWS上Ubuntu 18.04 new machine,需要进行以下安装:

sudo apt-get install gcc libpq-dev -y
sudo apt-get install python-dev  python-pip -y
sudo apt-get install python3-dev python3-pip python3-venv python3-wheel -y
pip3 install wheel

特别是最后一行是必须的。
但是,可能需要3行之前。

希望能有所帮助。

Jan 2020

2 hours wasted.

On a AWS Ubuntu 18.04 new machine, below installations are required:

sudo apt-get install gcc libpq-dev -y
sudo apt-get install python-dev  python-pip -y
sudo apt-get install python3-dev python3-pip python3-venv python3-wheel -y
pip3 install wheel

Especially the last line is must.
However before 3 lines might be required as prerequisites.

Hope that helps.


回答 3

该问题是由于:

  • 已为Python 2.7安装了旧版本的pip(6.1.1)
  • Trusty Beta映像上安装的Python 2.7的多个副本
  • 用于Python 2.7的其他位置 sudo

这一切都有点复杂,这里https://github.com/travis-ci/travis-ci/issues/4989可以更好地解释。

我的解决方案是使用user travis而非sudo

- pip2.7 install --upgrade --user travis pip setuptools wheel virtualenv

This problem is due to:

  • an old version of pip (6.1.1) being installed for Python 2.7
  • multiple copies of Python 2.7 installed on the Trusty Beta image
  • a different location for Python 2.7 being used for sudo

It’s all a bit complicated and better explained here https://github.com/travis-ci/travis-ci/issues/4989.

My solution was to install with user travis instead of sudo:

- pip2.7 install --upgrade --user travis pip setuptools wheel virtualenv

回答 4

如果已经安装了所有必需的模块,则可能需要将setuptools模块导入setup.py文件中。因此,只需在setup.py文件开头添加以下行。

import setuptools
from distutils.core import setup
# other imports and setups

Wheel的文档中也提到了这一点。https://wheel.readthedocs.io/en/stable/#usage

If you already have all the required modules installed you probably need to import the setuptools module in your setup.py file. So just add the following line at the leading of setup.py file.

import setuptools
from distutils.core import setup
# other imports and setups

This is also mentioned in wheel’s documentation. https://wheel.readthedocs.io/en/stable/#usage


回答 5

与许多建议的答案和不同的解决方案一样,此错误也很奇怪。我尝试过,添加它们。只有当我添加pip install --upgrade pip最终为我消除错误时。但是我没有时间隔离哪个是哪个,所以这只是一个问题。

This error is weird as many proposed answers and got mixed solutions. I tried them, add them. It was only when I added pip install --upgrade pip finally removed the error for me. But I have no time to isolate which is which,so this is just fyi.


回答 6

就我而言,venv创建的wheel / pip / setuptools版本太旧了。这有效:

venv/bin/pip  install --upgrade pip wheel setuptools

in my case, the version of wheel/pip/setuptools created by venv is too old. this works:

venv/bin/pip  install --upgrade pip wheel setuptools

回答 7

我已经wheel安装了,所以我尝试卸载并重新安装,它解决了此问题:

pip uninstall wheel
pip install wheel

奇怪的…

I already had wheel installed so I tried to uninstall and reinstall, and it fixed the issue:

pip uninstall wheel
pip install wheel

Weird…


回答 8

我的解决方法是 apt install python3-dev

My fix was apt install python3-dev


回答 9

在中setup.py,如果您有:

from distutils.core import setup

然后,将其更改为

from setuptools import setup

然后重新创建您的virtualenv并重新运行该命令,它应该可以工作。

In your setup.py, if you have:

from distutils.core import setup

Then, change it to

from setuptools import setup

Then re-create your virtualenv and re-run the command, and it should work.


回答 10

尝试通过从setuptools而不是distutils.core导入安装程序来修改setup.py文件

Try modifying the setup.py file by importing setup from setuptools instead of distutils.core


回答 11

apt-get install python3-dev在Ubuntu中做过,并添加setup_requires=["wheel"]setup.py

I did apt-get install python3-dev in my Ubuntu and added setup_requires=["wheel"] in setup.py


回答 12

它帮助我按照此处的说明进行操作:

https://packaging.python.org/guides/installing-using-linux-tools/

Debian / Ubuntu

Python 2:

sudo apt install python-pip

Python 3:

sudo apt install python3-venv python3-pip

It helped me to follow instructions in here:

https://packaging.python.org/guides/installing-using-linux-tools/

Debian/Ubuntu

Python 2:

sudo apt install python-pip

Python 3:

sudo apt install python3-venv python3-pip

回答 13

使用Ubuntu 18.04,可以通过安装python3-wheel软件包来解决此问题。

通常,它是作为对任何Python包的依赖项安装的。但是尤其是在构建容器映像时,您经常使用--no-install-recommends它,因此常常会丢失它,因此必须首先手动安装。

Using Ubuntu 18.04 this problem can be resolved by installing the python3-wheelpackage.

Usually this is installed as a dependency on any Python package. But especially when building container images you often work with --no-install-recommends and therefore it is often missing and has to be installed manually first.


回答 14

与Travis CI无关,但是尝试jupyter在Mac OSX 10.8.5上安装时遇到了类似的问题,其他答案都没有帮助。该问题是由于为名为“pyzmq,错误消息填充了数百页。

我发现的解决方案是直接安装该软件包的旧版本:

python -m pip install pyzmq==17 --user

之后,安装jupyter成功,没有错误。

Not related to Travis CI but I ran into similar problem trying to install jupyter on my Mac OSX 10.8.5, and none of the other answers was of help. The problem was caused by building the “wheel” for the package called pyzmq, with error messages filling hundreds of pages.

The solution I found was to directly install an older version of that package:

python -m pip install pyzmq==17 --user

After that, the installation of jupyter succeded without errors.


回答 15

如果您使用的是setup.cfg文件,请将其添加到install_require零件之前:

setup_requires =
    wheel

setup.cfg项目示例:

# setup.py
from setuptools import setup

setup()
# setup.cfg
[metadata]
name = name
version = 0.0.1
description = desc
long_description = file: README.md
long_description_content_type = text/markdown
url = url
author = author
classifiers =
    Programming Language :: Python
    Programming Language :: Python :: 3

[options]
include_package_data = true
packages = find:
setup_requires =
    wheel
install_requires =
    packages
    packages
    packages

If you’re using setup.cfg files, add this before the install_require part:

setup_requires =
    wheel

Example of setup.cfg project :

# setup.py
from setuptools import setup

setup()
# setup.cfg
[metadata]
name = name
version = 0.0.1
description = desc
long_description = file: README.md
long_description_content_type = text/markdown
url = url
author = author
classifiers =
    Programming Language :: Python
    Programming Language :: Python :: 3

[options]
include_package_data = true
packages = find:
setup_requires =
    wheel
install_requires =
    packages
    packages
    packages

错误:找不到vcvarsall.bat

问题:错误:找不到vcvarsall.bat

我试图安装Python软件包dulwich

pip install dulwich

但是我收到了一个神秘的错误消息:

error: Unable to find vcvarsall.bat

如果我尝试手动安装软件包,也会发生相同的情况:

> python setup.py install
running build_ext
building 'dulwich._objects' extension
error: Unable to find vcvarsall.bat

I tried to install the Python package dulwich:

pip install dulwich

But I get a cryptic error message:

error: Unable to find vcvarsall.bat

The same happens if I try installing the package manually:

> python setup.py install
running build_ext
building 'dulwich._objects' extension
error: Unable to find vcvarsall.bat

回答 0

更新:评论指出此处的说明可能很危险。考虑使用Visual C ++ 2008 Express版或专用于Python的Microsoft Visual C ++编译器详细信息),而不要使用下面的原始答案。原始错误消息表示未安装所需的Visual C ++版本。


对于Windows安装:

在运行setup.py进行软件包安装时,Python 2.7搜索已安装的Visual Studio2008。您可以通过VS90COMNTOOLS在调用之前在环境变量中设置正确的路径来诱使Python使用更新的Visual Studio setup.py

根据安装的Visual Studio版本执行以下命令:

  • Visual Studio 2010(VS10): SET VS90COMNTOOLS=%VS100COMNTOOLS%
  • Visual Studio 2012(VS11): SET VS90COMNTOOLS=%VS110COMNTOOLS%
  • Visual Studio 2013(VS12): SET VS90COMNTOOLS=%VS120COMNTOOLS%
  • Visual Studio 2015(VS14): SET VS90COMNTOOLS=%VS140COMNTOOLS%

警告:如下所述,如果您尝试编译python模块,则此答案不太可能起作用。

有关详细信息,请参见在Windows上为Python 2.7构建lxml

Update: Comments point out that the instructions here may be dangerous. Consider using the Visual C++ 2008 Express edition or the purpose-built Microsoft Visual C++ Compiler for Python (details) and NOT using the original answer below. Original error message means the required version of Visual C++ is not installed.


For Windows installations:

While running setup.py for package installations, Python 2.7 searches for an installed Visual Studio 2008. You can trick Python to use a newer Visual Studio by setting the correct path in VS90COMNTOOLS environment variable before calling setup.py.

Execute the following command based on the version of Visual Studio installed:

  • Visual Studio 2010 (VS10): SET VS90COMNTOOLS=%VS100COMNTOOLS%
  • Visual Studio 2012 (VS11): SET VS90COMNTOOLS=%VS110COMNTOOLS%
  • Visual Studio 2013 (VS12): SET VS90COMNTOOLS=%VS120COMNTOOLS%
  • Visual Studio 2015 (VS14): SET VS90COMNTOOLS=%VS140COMNTOOLS%

WARNING: As noted below, this answer is unlikely to work if you are trying to compile python modules.

See Building lxml for Python 2.7 on Windows for details.


回答 1

我找到了解决方案。我安装了“ amara”时遇到了完全相同的问题,并且出现了错误。我安装了mingw32,但需要配置distutils。

  1. 我已经安装了Python 2.6。
  2. 我安装了mingw32 C:\programs\mingw\
  3. 将mingw32的bin目录添加到您的环境变量中:附加c:\programs\MinGW\bin;PATH
  4. 编辑位于以下位置的distutils.cfg文件(如果不存在则创建)C:\Python26\Lib\distutils\distutils.cfg

    [build]
    compiler=mingw32
  5. 现在运行easy_install.exe amara

确保通过打开新环境来设置环境cmd.exe

I found the solution. I had the exact same problem, and error, installing ‘amara’. I had mingw32 installed, but distutils needed to be configured.

  1. I have Python 2.6 that was already installed.
  2. I installed mingw32 to C:\programs\mingw\
  3. Add mingw32’s bin directory to your environment variable: append c:\programs\MinGW\bin; to the PATH
  4. Edit (create if not existing) distutils.cfg file located at C:\Python26\Lib\distutils\distutils.cfg to be:

    [build]
    compiler=mingw32
    
  5. Now run easy_install.exe amara.

Make sure environment is set by opening a new cmd.exe.


回答 2

您可以从http://www.lfd.uci.edu/~gohlke/pythonlibs/安装编译版本


回答 3

如果要使用Visual Studio C ++而不是mingw进行编译…

  1. 运行python.exe以显示使用哪个版本的VC ++(如下所示的示例)。

    它是重要的使用Visual C ++编译器的相应版本的Python用,因为编译distilutilsget_build_version防止混合版本(每彼得的警告)。

    • 黄色(顶部)是使用MSC v.1500(Visual Studio C ++ 2008)编译的Python 2.7。
    • 红色(底部)是使用MSC v.1600(Visual Studio C ++ 2010)编译的Python 3.4.1。

  2. 使用下表[1]将内部VC ++版本与相应的Visual Studio版本进行匹配:

    MSC v.1000 -> Visual C++ 4.x        
    MSC v.1100 -> Visual C++ 5          
    MSC v.1200 -> Visual C++ 6          
    MSC v.1300 -> Visual C++ .NET       
    MSC v.1310 -> Visual C++ .NET 2003  
    MSC v.1400 -> Visual C++ 2005  (8.0)
    MSC v.1500 -> Visual C++ 2008  (9.0)
    MSC v.1600 -> Visual C++ 2010 (10.0)
    MSC v.1700 -> Visual C++ 2012 (11.0)
    MSC v.1800 -> Visual C++ 2013 (12.0)
    MSC v.1900 -> Visual C++ 2015 (14.0)
    MSC v.1910 -> Visual C++ 2017 (15.0)
    MSC v.1911 -> Visual C++ 2017 (15.3)
    MSC v.1912 -> Visual C++ 2017 (15.5)
    MSC v.1913 -> Visual C++ 2017 (15.6)
    MSC v.1914 -> Visual C++ 2017 (15.7)
    MSC v.1915 -> Visual C++ 2017 (15.8)
    MSC v.1916 -> Visual C++ 2017 (15.9)   
  3. 从上一步下载并安装相应版本的Visual Studio C ++。
    下面列出了特定版本VC ++的其他说明。

    Visual Studio C ++ 2008的注意事项

    对于只有 32位编译器,下载的Visual Studio C ++ 2008 Express版本

    对于64位编译器[2] [3],请下载Windows 7的Windows SDK和.NET Framework 3.5 SP1

    • 取消选中所有选项,Developer Tools >> Visual C++ Compilers以节省安装SDK工具所需的时间和磁盘空间,否则就不需要使用SDK工具。

    Visual Studio C ++ 2010的注意事项

    根据Microsoft的说法,如果安装了Visual Studio 2010 SP1,则可能已删除VC ++的编译器和库。
    如果是这种情况,请下载Visual C ++ 2010 SP1编译器更新

    Visual Studio C ++ 2015的注意事项

    如果不需要Visual Studio IDE,请下载Visual Studio C ++ 2015构建工具

    Visual Studio C ++ 2017的注意事项

    如果您不需要Visual Studio IDE,请下载Visual Studio 2017的构建工具

    建议:如果您同时安装了32位和64位Python,则可能还希望使用virtualenv创建单独的Python环境,以便一次可以使用一个或另一个,而无需弄乱选择要使用哪个Python版本的路径。采用。

根据@srodriguex的说法,您可以通过遵循以下答案,而不是将一些批处理文件复制到Python正在搜索的位置,从而跳过手动加载批处理文件的步骤(步骤4-6)。如果这不起作用,请执行以下最初对我有用的步骤。

  1. 开一个 cmd.exe

  2. 尝试安装需要C扩展的东西之前,请运行以下批处理文件以将VC ++编译器的环境加载到会话中(即环境变量,编译器的路径等)。

    执行:

    • 32位编译器:

      注意:32位Windows安装将仅C:\Program Files\符合预期

      "C:\Program Files (x86)\Microsoft Visual Studio 9.0\Common7\Tools\vsvars32.bat"

    • 64位编译器:

      "C:\Program Files (x86)\Microsoft Visual Studio 9.0\Common7\Tools\vsvars64.bat"

      注意:是的,本机64位编译器位于中Program Files (x86)。不要问我为什么。
      此外,如果您想知道vcvars64.bat和之间的区别,vcvarsx86_amd64.bat或者更重要的是amd64和之间的区别x86_amd64,则前者用于本机64位编译器工具,而后者是可以在32位Windows安装上运行的64位交叉编译器。 。

    更新:
    如果由于某种原因你得到error: ... was unexpected at this time.其中的...一些一系列字符,那么你需要检查你的路径变量没有任何多余的字符,如额外的报价或杂散字符。如果批处理文件最初没有意义,则将无法更新您的会话路径。

  3. 如果一切顺利,则应根据以下版本的VC ++和运行的命令获得以下消息之一:

    对于32位编译器工具:
    Setting environment for using Microsoft Visual Studio 20xx x86 tools.

    对于64位编译器工具:
    Setting environment for using Microsoft Visual Studio 20xx x64 tools.

  4. 现在,通过python setup.py install或运行设置pip install pkg-name

  5. 希望并用手指指望行星正确对齐,以使VC ++能够合作。

If you want to compile with Visual Studio C++ instead of mingw…

  1. Run python.exe to display which version of VC++ it was compiled with (example shown below).

    It is important to use the corresponding version of the Visual C++ compiler that Python was compiled with since distilutils‘s get_build_version prevents mixing versions (per Piotr’s warning).

    • Yellow (top) is Python 2.7, compiled with MSC v.1500 (Visual Studio C++ 2008)
    • Red (bottom) is Python 3.4.1, compiled with MSC v.1600 (Visual Studio C++ 2010)

  2. Use the table below[1] to match the internal VC++ version with the corresponding Visual Studio release:

    MSC v.1000 -> Visual C++ 4.x        
    MSC v.1100 -> Visual C++ 5          
    MSC v.1200 -> Visual C++ 6          
    MSC v.1300 -> Visual C++ .NET       
    MSC v.1310 -> Visual C++ .NET 2003  
    MSC v.1400 -> Visual C++ 2005  (8.0)
    MSC v.1500 -> Visual C++ 2008  (9.0)
    MSC v.1600 -> Visual C++ 2010 (10.0)
    MSC v.1700 -> Visual C++ 2012 (11.0)
    MSC v.1800 -> Visual C++ 2013 (12.0)
    MSC v.1900 -> Visual C++ 2015 (14.0)
    MSC v.1910 -> Visual C++ 2017 (15.0)
    MSC v.1911 -> Visual C++ 2017 (15.3)
    MSC v.1912 -> Visual C++ 2017 (15.5)
    MSC v.1913 -> Visual C++ 2017 (15.6)
    MSC v.1914 -> Visual C++ 2017 (15.7)
    MSC v.1915 -> Visual C++ 2017 (15.8)
    MSC v.1916 -> Visual C++ 2017 (15.9)   
    
  3. Download and install the corresponding version of Visual Studio C++ from the previous step.
    Additional notes for specific versions of VC++ are listed below.

    Notes for Visual Studio C++ 2008

    For only the 32-bit compilers, download Visual Studio C++ 2008 Express Edition.

    For the 64-bit compilers[2][3], download Windows SDK for Windows 7 and .NET Framework 3.5 SP1.

    • Uncheck everything except Developer Tools >> Visual C++ Compilers to save time and disk space from installing SDK tools you otherwise don’t need.

    Notes for Visual Studio C++ 2010

    According to Microsoft, if you installed Visual Studio 2010 SP1, it may have removed the compilers and libraries for VC++.
    If that is the case, download Visual C++ 2010 SP1 Compiler Update.

    Notes for Visual Studio C++ 2015

    If you don’t need the Visual Studio IDE, download Visual Studio C++ 2015 Build Tools.

    Notes for Visual Studio C++ 2017

    If you don’t need the Visual Studio IDE, download Build Tools for Visual Studio 2017.

    Suggestion: If you have both a 32- and 64-bit Python installation, you may also want to use virtualenv to create separate Python environments so you can use one or the other at a time without messing with your path to choose which Python version to use.

According to @srodriguex, you may be able to skip manually loading the batch file (Steps 4-6) by instead copying a few batch files to where Python is searching by following this answer. If that doesn’t work, here are the following steps that originally worked for me.

  1. Open up a cmd.exe

  2. Before you try installing something which requires C extensions, run the following batch file to load the VC++ compiler’s environment into the session (i.e. environment variables, the path to the compiler, etc).

    Execute:

    • 32-bit Compilers:

      Note: 32-bit Windows installs will only have C:\Program Files\ as expected

      "C:\Program Files (x86)\Microsoft Visual Studio 9.0\Common7\Tools\vsvars32.bat"

    • 64-bit Compilers:

      "C:\Program Files (x86)\Microsoft Visual Studio 9.0\Common7\Tools\vsvars64.bat"

      Note: Yes, the native 64-bit compilers are in Program Files (x86). Don’t ask me why.
      Additionally, if you are wondering what the difference between vcvars64.bat and vcvarsx86_amd64.bat or more importantly the difference between amd64 and x86_amd64, the former are for the native 64-bit compiler tools and the latter are the 64-bit cross compilers that can run on a 32-bit Windows installation.

    Update:
    If for some reason you are getting error: ... was unexpected at this time. where the ... is some series of characters, then you need to check that you path variable does not have any extraneous characters like extra quotations or stray characters. The batch file is not going to be able to update your session path if it can’t make sense of it in the first place.

  3. If that went well, you should get one of the following messages depending on which version of VC++ and which command you ran:

    For the 32-bit compiler tools:
    Setting environment for using Microsoft Visual Studio 20xx x86 tools.

    For the 64-bit compiler tools:
    Setting environment for using Microsoft Visual Studio 20xx x64 tools.

  4. Now, run the setup via python setup.py install or pip install pkg-name

  5. Hope and cross your fingers that the planets are aligned correctly for VC++ to cooperate.


回答 4

这是怎么回事?Python模块可以用C或C ++编写(通常是为了提高速度)。如果尝试使用Pip(或setup.py)安装这样的软件包,则必须从源代码编译该C / C ++。开箱即用,Pip会大胆假设您已安装了Microsoft Visual C ++编译器。如果没有它,您将看到此错误消息“错误:无法找到vcvarsall.bat”。

规定的解决方案是安装C / C ++编译器,Microsoft Visual C ++或MinGW(一个开源项目)。但是,安装和配置任何一个都非常困难。(编辑2014:Microsoft已发布了用于Python 2.7 的特殊C ++编译器

最简单的解决方案是将Christoph Gohlke的Windows安装程序(.msi)用于流行的Python软件包。他为Python 2.x和3.x,32位和64位构建安装程序。您可以从http://www.lfd.uci.edu/~gohlke/pythonlibs/下载它们


如果您也认为“错误:无法找到vcvarsall.bat”是一个含糊不清和无用的消息,请在http://bugs.python.org/issue2943上对该错误进行评论,以更有用和更用户化的方式替换它。友好的消息。

为了进行比较,Ruby附带了软件包管理器Gem,并提供了一个准官方的C / C ++编译器DevKit。如果您尝试安装不带该软件包的软件包,则会看到此有用的友好有用消息:

请更新您的PATH以包含构建工具,或从http://rubyinstaller.org/downloads下载DevKit 并按照http://github.com/oneclick/rubyinstaller/wiki/Development-Kit上的说明进行操作

您可以在https://stackoverflow.com/a/13445719/284795上阅读有关Python打包的更长篇文章

What’s going on? Python modules can be part written in C or C++ (typically for speed). If you try to install such a package with Pip (or setup.py), it has to compile that C/C++ from source. Out the box, Pip will brazenly assume you the compiler Microsoft Visual C++ installed. If you don’t have it, you’ll see this cryptic error message “Error: Unable to find vcvarsall.bat”.

The prescribed solution is to install a C/C++ compiler, either Microsoft Visual C++, or MinGW (an open-source project). However, installing and configuring either is prohibitively difficult. (Edit 2014: Microsoft have published a special C++ compiler for Python 2.7)

The easiest solution is to use Christoph Gohlke’s Windows installers (.msi) for popular Python packages. He builds installers for Python 2.x and 3.x, 32 bit and 64 bit. You can download them from http://www.lfd.uci.edu/~gohlke/pythonlibs/


If you too think “Error: Unable to find vcvarsall.bat” is a ludicrously cryptic and unhelpful message, then please comment on the bug at http://bugs.python.org/issue2943 to replace it with a more helpful and user-friendly message.

For comparison, Ruby ships with a package manager Gem and offers a quasi-official C/C++ compiler, DevKit. If you try to install a package without it, you see this helpful friendly useful message:

Please update your PATH to include build tools or download the DevKit from http://rubyinstaller.org/downloads and follow the instructions at http://github.com/oneclick/rubyinstaller/wiki/Development-Kit

You can read a longer rant about Python packaging at https://stackoverflow.com/a/13445719/284795


回答 5

您需要安装与用于构建Python的编译器兼容的Microsoft编译器。这意味着您需要Visual C ++ 2008(或更高版本,需要进行一些调整)。

微软现在提供一个捆绑的编译器和头能够编译Python扩展,在好记的网址:

适用于Python 2.7的Microsoft Visual C ++编译器

http://aka.ms/vcpython27

这是一个相对较小的包装;下载85MB,无需管理员权限即可安装,无需重新启动。名称有点误导,该编译器适用于最初使用Visual C ++ 2008编译的任何Python版本,而不仅仅是Python 2.7。

如果您启动Python交互式提示或print sys.version,请查找MSC版本字符串;否则,请执行以下操作:如果是这样,MSC v.1500您可以使用此工具。

原始公告到distutils列表

微软已经发布了适用于Python 2.7的编译器软件包,以使人们可以更轻松地在Windows上构建和分发C扩展模块。可从以下网站获得用于Python 2.7的Microsoft Visual C ++编译器(aka VC9):http : //aka.ms/vcpython27

该软件包包含为32位和64位Python 2.7构建C扩展模块所需的所有工具和头文件(请注意,某些扩展模块需要第三方的依赖项,例如OpenSSL或libxml2,但不包括在内)。还支持使用Visual C ++ 2008构建的其他Python版本,因此“ Python 2.7”仅是广告-可以在2.6和3.2上正常工作。

请注意,您需要安装setuptools6.0或更高版本(在下载页面的系统要求中列出)。您正在安装的项目必须使用setuptools.setup(),而不是,distutils否则自动检测将不起作用。

Microsoft已声明他们希望保持URL稳定,以便自动脚本可以轻松引用它。

You’ll need to install a Microsoft compiler, compatible with the compiler used to build Python. This means you need Visual C++ 2008 (or newer, with some tweaking).

Microsoft now supplies a bundled compiler and headers just to be able to compile Python extensions, at the memorable URL:

Microsoft Visual C++ Compiler for Python 2.7

http://aka.ms/vcpython27

This is a relatively small package; 85MB to download, installable without admin privileges, no reboot required. The name is a little misleading, the compiler will work for any Python version originally compiled with Visual C++ 2008, not just Python 2.7.

If you start a Python interactive prompt or print sys.version, look for the MSC version string; if it is MSC v.1500 you can use this tool.

From the original announcement to the distutils list:

Microsoft has released a compiler package for Python 2.7 to make it easier for people to build and distribute their C extension modules on Windows. The Microsoft Visual C++ Compiler for Python 2.7 (a.k.a. VC9) is available from: http://aka.ms/vcpython27

This package contains all the tools and headers required to build C extension modules for Python 2.7 32-bit and 64-bit (note that some extension modules require 3rd party dependencies such as OpenSSL or libxml2 that are not included). Other versions of Python built with Visual C++ 2008 are also supported, so “Python 2.7” is just advertising – it’ll work fine with 2.6 and 3.2.

Note that you need to have setuptools 6.0 or newer installed (listed in the system requirements on the download page). The project you are installing must use setuptools.setup(), not distutils or the auto-detection won’t work.

Microsoft has stated that they want to keep the URL stable, so that automated scripts can reference it easily.


回答 6

我只是遇到了同样的问题,所以我在这里讲述我的故事,希望它可以帮助遇到同样问题的其他人,并为他们节省几个小时的时间:

我在Windows 7盒子中有mingw(g ++(GCC)4.6.1)和python 2.7.3,我正在尝试安装PyCrypto。

运行setup.py install时,所有错误均始于此错误:

error: Unable to find vcvarsall.bat

通过将mingw指定为选择的编译器,可以轻松地在搜索错误之后解决此问题:

setup.py install build --compiler=mingw32

问题是然后我得到了另一个错误:

configure: error: cannot run C compiled programs.

事实证明,我的防病毒软件阻止了新编译的.exe的执行。我只是禁用了防病毒“居民防护罩”,然后转到下一个错误:

cc1.exe: error: unrecognized command line option '-mno-cygwin' 
error: command 'gcc' failed with exit status 1

解决了它:“要么安装稍旧版本的MinGW,要么在您的Python目录中编辑distutils \ cygwinccompiler.py以删除-mno-cygwin的所有实例。” (从这里开始

现在,我终于可以开始工作了。

I just had this same problem, so I’ll tell my story here hoping it helps someone else with the same issues and save them the couple of hours I just spent:

I have mingw (g++ (GCC) 4.6.1) and python 2.7.3 in a windows 7 box and I’m trying to install PyCrypto.

It all started with this error when running setup.py install:

error: Unable to find vcvarsall.bat

Easily solved after googling the error by specifying mingw as the compiler of choice:

setup.py install build --compiler=mingw32

The problem is that then I got a different error:

configure: error: cannot run C compiled programs.

It turns out that my anti-virus was blocking the execution of a freshly compiled .exe. I just disabled the anti-virus “resident shield” and went to the next error:

cc1.exe: error: unrecognized command line option '-mno-cygwin' 
error: command 'gcc' failed with exit status 1

This solved it: “Either install a slightly older version of MinGW, or edit distutils\cygwinccompiler.py in your Python directory to remove all instances of -mno-cygwin.” (from here)

Now, I can finally start working.


回答 7

看起来它正在寻找VC编译器,因此您可以尝试使用来提及编译器类型-c mingw32,因为您拥有msys

python setup.py install -c mingw32

Looks like its looking for VC compilers, so you could try to mention compiler type with -c mingw32, since you have msys

python setup.py install -c mingw32

回答 8

我有python 2.73和Windows 7。对我有用的解决方案是:

  1. 新增的mingw32的bin目录到环境变量:追加PATHC:\programs\mingw\bin;
  2. 创建的distutils.cfg位于C:\Python27\Lib\distutils\distutils.cfg

    [build]
    compiler=mingw32

要处理MinGW不再识别-mno-cygwin标志的情况,请删除C:\ Python27 \ Lib \ distutils \ cygwincompiler.py第322行至326行中的标志,因此如下所示:

  self.set_executables(compiler='gcc -O -Wall',
                         compiler_so='gcc -mdll -O -Wall',
                         compiler_cxx='g++ -O -Wall',
                         linker_exe='gcc',
                         linker_so='%s %s %s'
                                    % (self.linker_dll, shared_option,
                                       entry_point))

I have python 2.73 and windows 7 .The solution that worked for me was:

  1. Added mingw32’s bin directory to environment variable: append PATH with C:\programs\mingw\bin;
  2. Created distutils.cfg located at C:\Python27\Lib\distutils\distutils.cfg containing:

    [build]
    compiler=mingw32
    

To deal with MinGW not recognizing the -mno-cygwin flag anymore, remove the flag in C:\Python27\Lib\distutils\cygwincompiler.py line 322 to 326, so it looks like this:

  self.set_executables(compiler='gcc -O -Wall',
                         compiler_so='gcc -mdll -O -Wall',
                         compiler_cxx='g++ -O -Wall',
                         linker_exe='gcc',
                         linker_so='%s %s %s'
                                    % (self.linker_dll, shared_option,
                                       entry_point))

回答 9

查看setup.py您要安装的软件包的文件。如果是较旧的软件包,则可能是导入distutils.core.setup()而不是setuptools.setup()

我在2015年遇到了以下这些因素:

  1. 来自http://aka.ms/vcpython27的适用于Python 2.7的Microsoft Visual C ++编译器

  2. 使用较旧的软件包 distutils.core.setup()

  3. 尝试做python setup.py build而不是使用pip

如果您使用的是最新版本的pip,则它将强制(monkeypatch)软件包使用setuptools,即使其setup.py对distutils的调用也是如此。但是,如果您不使用pip而是在做python setup.py build,则构建过程将使用distutils.core.setup(),而后者不知道编译器的安装位置。


步骤1:打开适当的Visual C ++ 2008命令提示符

打开“开始”菜单或“开始”屏幕,然后搜索“ Visual C ++ 2008 32位命令提示符”(如果您的Python是32位)或“ Visual C ++ 2008 64位命令提示符”(如果您的Python是64位) 。运行。命令提示符在标题栏中应显示Visual C ++ 2008…。

步骤2:设定环境变数

在刚打开的命令提示符中设置这些环境变量。

SET DISTUTILS_USE_SDK=1
SET MSSdk=1

参考http://bugs.python.org/issue23246

步骤3:建立并安装

cd到要构建并运行的包python setup.py build,然后python setup.py install。如果要安装到virtualenv,请在构建之前将其激活。

Look in the setup.py file of the package you are trying to install. If it is an older package it may be importing distutils.core.setup() rather than setuptools.setup().

I ran in to this (in 2015) with a combination of these factors:

  1. The Microsoft Visual C++ Compiler for Python 2.7 from http://aka.ms/vcpython27

  2. An older package that uses distutils.core.setup()

  3. Trying to do python setup.py build rather than using pip.

If you use a recent version of pip, it will force (monkeypatch) the package to use setuptools, even if its setup.py calls for distutils. However, if you are not using pip, and instead are just doing python setup.py build, the build process will use distutils.core.setup(), which does not know about the compiler install location.


Solution

Step 1: Open the appropriate Visual C++ 2008 Command Prompt

Open the Start menu or Start screen, and search for “Visual C++ 2008 32-bit Command Prompt” (if your python is 32-bit) or “Visual C++ 2008 64-bit Command Prompt” (if your python is 64-bit). Run it. The command prompt should say Visual C++ 2008 … in the title bar.

Step 2: Set environment variables

Set these environment variables in the command prompt you just opened.

SET DISTUTILS_USE_SDK=1
SET MSSdk=1

Reference http://bugs.python.org/issue23246

Step 3: Build and install

cd to the package you want to build, and run python setup.py build, then python setup.py install. If you want to install in to a virtualenv, activate it before you build.


回答 10

也许有人会感兴趣,以下对py2exe软件包有用。(我有Windows 7 64位和便携式python 2.7,带有适用于Windows 7和.NET Framework 4的Windows SDK的Visual Studio 2005 Express)

set VS90COMNTOOLS=%VS80COMNTOOLS%

然后:

python.exe setup.py install

Maybe somebody can be interested, the following worked for me for the py2exe package. (I have windows 7 64 bit and portable python 2.7, Visual Studio 2005 Express with Windows SDK for Windows 7 and .NET Framework 4)

set VS90COMNTOOLS=%VS80COMNTOOLS%

then:

python.exe setup.py install

回答 11

我花了将近2天的时间弄清楚如何在python 3.4 64位版本中解决此问题:Python 3.4.3(v3.4.3:9b73f1c3e601,Feb 24 2015,22:44:40)[MSC v.1600 64位(AMD64 )]在win32上

困难的解决方案1 ​​:(在阅读本文之前,请先阅读下面的解决方案2)最后,这对我有帮助:

  1. 安装Visual C ++ 2010 Express
  2. 为Windows 7安装Microsoft Windows SDK v7.1
  3. 手动创建文件vcvars64.batC:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\bin\amd64其中包含CALL "C:\Program Files\Microsoft SDKs\Windows\v7.1\Bin\SetEnv.cmd" /x64或其他路径,具体取决于安装位置
  4. (这似乎是可选的)针对Windows SDK 7.1安装Microsoft Visual Studio 2010 Service Pack 1以及Microsoft Visual C ++ 2010 Service Pack 1编译器更新
  5. 之后,我尝试pip install numpy但收到以下错误:

    File "numpy\core\setup.py", line 686, in get_mathlib_info
    raise RuntimeError("Broken toolchain: cannot link a simple C program")
    RuntimeError: Broken toolchain: cannot link a simple C program

    我改mfinfoNoneC:\Python34\Lib\distutils\msvc9compiler.py每本https://stackoverflow.com/a/23099820/4383472

  6. 最终在pip install numpy命令后,我的avast防病毒软件试图干扰安装过程,但我很快将其禁用

花费了很长时间-numpy编译了几分钟,我什至以为出现了错误,但最终一切都OK。

解决方案2,简单:( 我知道这种方法已经在高度投票的答案中提到过,但是由于它确实更容易,所以让我重复一下)经过所有这些工作之后,我了解到对我来说最好的方法就是使用将来可从http://www.lfd.uci.edu/~gohlke/pythonlibs/预编译二进制文件。我极少需要此网站不包含的某些软件包(或软件包的版本)。这种方式的安装过程也更快。例如,安装numpy

  1. numpy‑1.9.2+mkl‑cp34‑none‑win_amd64.whl从该站点下载(如果您具有Python 3.4 64位)
  2. 在命令提示符或Powershell中使用pip安装pip install numpy‑1.9.2+mkl‑cp34‑none‑win_amd64.whl(或文件的完整路径,具体取决于打开命令提示符的方式)

I spent almost 2 days figuring out how to fix this problem in my python 3.4 64 bit version: Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 24 2015, 22:44:40) [MSC v.1600 64 bit (AMD64)] on win32

Solution 1, hard: (before reading this, read first Solution 2 below) Finally, this is what helped me:

  1. install Visual C++ 2010 Express
  2. install Microsoft Windows SDK v7.1 for Windows 7
  3. create manually file vcvars64.bat in C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\bin\amd64 which contains CALL "C:\Program Files\Microsoft SDKs\Windows\v7.1\Bin\SetEnv.cmd" /x64 or other path depending on where you have yours installed
  4. (this seems to be optional) install Microsoft Visual Studio 2010 Service Pack 1 together with Microsoft Visual C++ 2010 Service Pack 1 Compiler Update for the Windows SDK 7.1
  5. after that I tried to pip install numpy but received the following error:

    File "numpy\core\setup.py", line 686, in get_mathlib_info
    raise RuntimeError("Broken toolchain: cannot link a simple C program")
    RuntimeError: Broken toolchain: cannot link a simple C program
    

    I changed mfinfo to None in C:\Python34\Lib\distutils\msvc9compiler.py per this https://stackoverflow.com/a/23099820/4383472

  6. finally after pip install numpy command my avast antivirus tried to interfere into the installation process, but i quickly disabled it

It took very long – several minutes for numpy to compile, I even thought that there was an error, but finally everything was ok.

Solution 2, easy: (I know this approach has already been mentioned in a highly voted answer, but let me repeat since it really is easier) After going through all of this work I understood that the best way for me is just to use already precompiled binaries from http://www.lfd.uci.edu/~gohlke/pythonlibs/ in future. There is very small chance that I will ever need some package (or a version of a package) which this site doesn’t contain. The installation process is also much quicker this way. For example, to install numpy:

  1. donwload numpy‑1.9.2+mkl‑cp34‑none‑win_amd64.whl (if you have Python 3.4 64-bit) from that site
  2. in command prompt or powershell install it with pip pip install numpy‑1.9.2+mkl‑cp34‑none‑win_amd64.whl (or full path to the file depending how command prompt is opened)

回答 12

我想在Windows 10上的python 2.7下运行pysph并找不到vcvarsall.bat(来自distutils)

我的解决方案如下:

为Python 2.7安装Microsoft Visual C ++(建议@Michael)

在Windows 10上,它已安装到(我的用户名是Andreas):

C:\Users\Andreas\AppData\Local\Programs\Common\Microsoft\Visual C++ for Python\9.0

设置环境变量VS90COMNTOOLS为Visual C ++ for Python 2.7的安装路径(请参见上面的路径)。

如果仍然无法使用,请在模块中进行修改

C:/Python27/lib/distutils

文件msvc9compiler.py。在其中找到功能find_vcvarsall并进行以下修改。

替换行:

productdir = os.path.join(toolsdir, os.pardir, os.pardir, "VC")

productdir = os.path.join(toolsdir)

在我的情况下,这就是vcvarsall.bat所在的位置(请检查vcvarsall.bat在您的安装位置中)。

I wanted to run pysph on Windows 10 under Python 2.7 and got vcvarsall.bat was not found (from distutils)

My solution was the following:

Install Microsoft Visual C++ for Python 2.7 (like @Michael suggested)

On Windows 10 it was installed into (my username is Andreas):

C:\Users\Andreas\AppData\Local\Programs\Common\Microsoft\Visual C++ for Python\9.0

Set environment variable VS90COMNTOOLS to the installation path of Visual C++ for Python 2.7 (see above path).

If it still doesn’t work, then modifiy in the module

C:/Python27/lib/distutils

the file msvc9compiler.py. Find in it the function find_vcvarsall and do following modification.

Replace the line:

productdir = os.path.join(toolsdir, os.pardir, os.pardir, "VC")

with

productdir = os.path.join(toolsdir)

This is where vcvarsall.bat resides in my case (check, where vcvarsall.bat is in your installation).


回答 13

当我尝试在python 3.5上安装numpy库时遇到此问题。解决的办法是安装VS2015。我有VS2008、2012、2013,其中没有一个与python 3.5兼容。显然,较新版本的python依赖于较新版本的VS。

还要确保Visual Studio已安装C ++通用工具。

I encountered this issue when I tried to install numpy library on my python 3.5. The solution is to install VS2015. I had VS2008, 2012, 2013, none of which is compatible with python 3.5. Apparently newer version of python has dependency on newer versions of VS.

Also make sure C++ Common Tools are installed with Visual Studio.


回答 14

我尝试了上述所有答案,但发现它们都不起作用,这可能是我使用Windows 8并安装了Visual Studio2012。在这种情况下,这就是您要做的。

vcvarsall.bat文件位于此处: C:\Program Files (x86)\Microsoft Visual Studio 11.0\VC

只需选择文件,然后将其复制。

然后转到此目录: C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\Tools

并粘贴文件。然后,一切都会好起来。

I tried all the above answers, and found all of them not to work, this was perhaps I was using Windows 8 and had installed Visual Studio 2012. In this case, this is what you do.

The vcvarsall.bat file is located here: C:\Program Files (x86)\Microsoft Visual Studio 11.0\VC

Simply select the file, and copy it.

Then go to this directory: C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\Tools

and paste the file. And then, all should be well.


回答 15

您可以从http://go.microsoft.com/?linkid=7729279下载免费的Visual C ++ 2008 Express Edition ,它将在安装过程中设置VS90COMNTOOLS环境变量,并因此使用兼容的编译器进行构建。

正如@PiotrDobrogost在评论中提到的那样,他对另一个问题的回答详细介绍了为什么要使用Visual C ++ 2008构建正确的东西,但是随着Windows的Python构建转移到更新版本的Visual Studio,这种情况可能会改变:构建lxml适用于Windows上的Python 2.7

You can download the free Visual C++ 2008 Express Edition from http://go.microsoft.com/?linkid=7729279, which will set the VS90COMNTOOLS environment variable during installation and therefore build with a compatible compiler.

As @PiotrDobrogost mentioned in a comment, his answer to this other question goes into details about why Visual C++ 2008 is the right thing to build with, but this can change as the Windows build of Python moves to newer versions of Visual Studio: Building lxml for Python 2.7 on Windows


回答 16

在Windows 7 x64上使用Python 3.4.1遇到了这个问题,不幸的是,我需要的软件包没有合适的exe或wheel可供使用。该系统需要一些“解决方法”,下面对此进行了详细说明(底部是TLDR)。

使用上面Jaxrtech的答案中的信息,我确定我需要Visual Studio C ++ 2010(sys.version返回MSC v.1600),因此我从他的答案中的链接http://go.microsoft安装了Visual C ++ 2010 Express。.com /?linkid = 9709949。我安装了所有带有更新的内容,但是正如您在下面看到的那样,这是一个错误。此时仅应安装Express的原始版本(不更新任何内容)。

vcvarsall.bat现在存在,但是在安装软件包时出现了新错误query_vcvarsall raise ValueError(str(list(result.keys())))ValueError: [u'path']。还有其他与此错误有关的stackoverflow问题,例如为Python 2.7构建/安装C模块时出现的错误

根据该答案,我确定2010 Express仅安装32位编译器。要获取64位(和其他)编译器,您需要安装Windows 7.1 SDK。请参阅http://msdn.microsoft.com/en-us/windowsserver/bb980924.aspx

但是,这不会为我安装,安装程序返回了错误installation failed with return code 5100。我在以下链接中找到了解决方案:http : //support.microsoft.com/kb/2717426。简而言之,如果安装了x86和x64 Microsoft Visual C ++ 2010 Redistributable的较新版本,它们将与SDK安装程序中的版本冲突,因此需要先进行卸载。

然后安装了SDK,但是我注意到vcvars64.bat仍然不存在C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\bin,也没有其子文件夹。vcvarsall.bat运行vcvars64批处理文件,因此如果没有该文件,python软件包仍将无法安装(我忘记了此时显示的错误)。

然后 ,我在这里找到了一些说明:http : //www.cryptohaze.com/wiki/index.php/Windows_7_Build_Setup#Download_VS_2010_and_Windows_SDK_7.1按照说明,我已经安装了Express和7.1 SDK,因此安装了SDK 7.1 SP1,并做了缺少头文件修复。然后,我使用content手动创建vcvars64.bat CALL setenv /x64。我将所有这些说明粘贴在这里,以免丢失。

步骤1是下载Visual Studio Express 2010。

http://www.microsoft.com/visualstudio/zh-cn/products/2010-editions/express 是一个不错的起点。下载安装程序,然后运行它(vc_web.exe)。您不需要SQL 2008的其他下载。

对于64位编译器,您还需要Windows SDK(当前为7.1)-除非您只想进行32位构建,否则将不完全支持…

http://www.microsoft.com/zh-cn/download/details.aspx?id=8279是下载此文件的好起点-下载后,您将要运行winsdk_web.exe!

这里的默认安装就可以了。

最后,下载并安装Windows SDK 7.1 SP1更新:http : //www.microsoft.com/zh-cn/download/details.aspx?id=4422

并且,要修复缺少的头文件,VS2010 SP1。 http://www.microsoft.com/downloads/zh-CN/confirmation.aspx?FamilyID=75568aa6-8107-475d-948a-ef22627e57a5

而且,该死的,为VS2010 Express修复丢失的批处理文件。这真是荒唐可笑。

在C:\ Program Files(x86)\ Microsoft Visual Studio 10.0 \ VC \ bin \ amd64中,使用以下命令创建“ vcvars64.bat”(您将需要以管理员身份运行):

呼叫setenv / x64

我的python软件包仍然没有安装(无法回忆起错误)。然后,我找到了一些使用特殊的SDK 7.1命令提示符的说明(在下面复制),请参阅:https : //mail.python.org/pipermail/distutils-sig/2012-February/018300.html

没关系,这个问题。此处有人在菜单上注意到此项目:开始->所有程序-> Microsoft Windows SDK v7.1-> Windows SDK 7.1命令提示符

这将运行一个批处理作业,该作业似乎为编译器设置了工作环境。在该提示下,您可以键入“ setup.py build”或“ setup.py install”。

我按照指示打开了Windows SDK 7.1命令提示符,并使用它在python软件包上运行easy_install。最后,成功!


TLDR ;

  1. 安装Visual Studio Express 2010(最好没有更新的可再发行文件或SQL Server)。
  2. 安装Windows 7.1 SDK
  3. Instal SDK 7.1 SP1更新和VS2010 SP1标头文件修复(可能不需要此步骤)。
  4. 手动创建C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\bin\amd64\vcvars64.bat内容CALL setenv /x64
  5. 开始->所有程序-> Microsoft Windows SDK v7.1-> Windows SDK 7.1命令提示符以打开特殊的x64命令提示符,然后可以将其与python / easy_install / pip / etc(包括virtual_envs中的命令)一起使用。

I had this problem using Python 3.4.1 on Windows 7 x64, and unfortunately the packages I needed didn’t have suitable exe or wheels that I could use. This system requires a few ‘workarounds’, which are detailed below (and TLDR at bottom).

Using the info in Jaxrtech’s answer above, I determined I needed Visual Studio C++ 2010 (sys.version return MSC v.1600), so I installed Visual C++ 2010 Express from the link in his answer, which is http://go.microsoft.com/?linkid=9709949. I installed everything with updates, but as you can read below, this was a mistake. Only the original version of Express should be installed at this time (no updated anything).

vcvarsall.bat was now present, but there was a new error when installing the package, query_vcvarsall raise ValueError(str(list(result.keys())))ValueError: [u'path']. There are other stackoverflow questions with this error, such as Errors while building/installing C module for Python 2.7

I determined from that answer that 2010 Express only installs 32-bit compilers. To get 64-bit (and other) compilers, you need to install Windows 7.1 SDK. See http://msdn.microsoft.com/en-us/windowsserver/bb980924.aspx

This would not install for me though, and the installer returned the error installation failed with return code 5100. I found the solution at the following link: http://support.microsoft.com/kb/2717426. In short, if newer versions of x86 and x64 Microsoft Visual C++ 2010 Redistributable’s are installed, they conflict with the ones in SDK installer, and need uninstalling first.

The SDK then installed, but I noticed vcvars64.bat still did not exist in C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\bin, nor its subfolders. vcvarsall.bat runs the vcvars64 batch file, so without it, the python package still wouldn’t install (I forgot the error that was shown at this time).

I then found some instructions here: http://www.cryptohaze.com/wiki/index.php/Windows_7_Build_Setup#Download_VS_2010_and_Windows_SDK_7.1 Following the instructions, I had already installed Express and 7.1 SDK, so installed SDK 7.1 SP1, and did the missing header file fix. I then manually created vcvars64.bat with the content CALL setenv /x64. I will paste all those instructions here, so they don’t get lost.

Step 1 is to download Visual Studio Express 2010.

http://www.microsoft.com/visualstudio/en-us/products/2010-editions/express is a good place to start. Download the installer, and run it (vc_web.exe). You don’t need the SQL 2008 additional download.

You’ll also need the Windows SDK (currently 7.1) for the 64-bit compilers – unless you want to do 32-bit only builds, which are not fully supported…

http://www.microsoft.com/en-us/download/details.aspx?id=8279 is a good starting point to download this – you’ll want to run winsdk_web.exe when downloaded!

The default install here is just fine.

Finally, download and install the Windows SDK 7.1 SP1 update: http://www.microsoft.com/en-us/download/details.aspx?id=4422

And, to fix missing header file, VS2010 SP1. http://www.microsoft.com/downloads/en/confirmation.aspx?FamilyID=75568aa6-8107-475d-948a-ef22627e57a5

And, bloody hell, fix the missing batch file for VS2010 Express. This is getting downright absurd.

In C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\bin\amd64, create “vcvars64.bat” with the following (you will need to be running as administrator):

CALL setenv /x64

My python package still did not install (can’t recall error). I then found some instructions (copied below) to use the special SDK 7.1 Command Prompt, see: https://mail.python.org/pipermail/distutils-sig/2012-February/018300.html

Never mind this question. Somebody here noticed this item on the menu: Start->All Programs->Microsoft Windows SDK v7.1 ->Windows SDK 7.1 Command Prompt

This runs a batch job that appears to set up a working environment for the compiler. From that prompt, you can type “setup.py build” or “setup.py install”.

I opened the Windows SDK 7.1 Command Prompt as instructed, and used it to run easy_install on the python package. And at last, success!


TLDR;

  1. Install Visual Studio Express 2010 (preferably without updated redistributables or SQL server).
  2. Install Windows 7.1 SDK
  3. Instal SDK 7.1 SP1 update, and VS2010 SP1 header file fix (this step may not be required).
  4. Manually create C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\bin\amd64\vcvars64.bat with content CALL setenv /x64
  5. Start->All Programs->Microsoft Windows SDK v7.1 ->Windows SDK 7.1 Command Prompt to open special x64 command prompt, which can then be used with python/easy_install/pip/etc (including those in virtual_envs).

回答 17

下面的步骤为我解决了这个问题,我试图用cython扩展创建安装程序。

  1. 安装适用于Python 2.7的Microsoft Visual C ++编译器
  2. 默认安装位置为@ C:\ Users \ PC-user \ AppData \ Local \ Programs \ Common \ Microsoft \ Visual C ++ for Python。这实际上可以解决此问题,请在继续操作之前进行一次测试。
  3. 如果失败,请检查VC ++中python vcvarsall.bat文件的位置。
  4. 在记事本中打开distutils软件包的msvc9compiler.py文件。
  5. 在我的框中,这是该文件中的@ C:\ Anaconda2 \ Lib \ distutils \ msvc9compiler.py find_vcvarsall函数,通过打印出版本参数来确定VC的版本。对于Python 2.7,可能是9.0
  6. 现在创建一个环境变量VS90COMNTOOLS,指向C:\ Users \ PC-user \ AppData \ Local \ Programs \ Common \ Microsoft \ Visual C ++ for Python \ 9.0 \ VC \ bin
  7. 由于某种原因,distutils期望vcvarsall.bat文件位于VC目录中,但是python工具的VC ++在9.0的根目录中有此文件。要解决此问题,请从path.join中删除“ VC”(大约在247行附近)

    #productdir = os.path.join(toolsdir, os.pardir, os.pardir, "VC") productdir = os.path.join(toolsdir, os.pardir, os.pardir)

上面的步骤为我解决了这个问题。

Below steps fixed this issue for me, I was trying to create setup with cython extension.

  1. Install Microsoft Visual C++ Compiler for Python 2.7
  2. The default install location would be @ C:\Users\PC-user\AppData\Local\Programs\Common\Microsoft\Visual C++ for Python This might actually fix the issue, test once before proceeding.
  3. If it fails, Check where in VC++ for python vcvarsall.bat file is located
  4. Open the msvc9compiler.py file of distutils package in notepad.
  5. In my box this was @ C:\Anaconda2\Lib\distutils\msvc9compiler.py find_vcvarsall function in this file, determine the version of VC by printing out version argument. For Python 2.7 it’s likely to be 9.0
  6. Now create an environment variable VS90COMNTOOLS, Pointing to C:\Users\PC-user\AppData\Local\Programs\Common\Microsoft\Visual C++ for Python\9.0\VC\bin
  7. For some reason distutils expects the vcvarsall.bat file to be within VC dir, but VC++ for python tools has it in the root of 9.0 To fix this, remove “VC” from the path.join (roughly around line 247)

    #productdir = os.path.join(toolsdir, os.pardir, os.pardir, "VC") productdir = os.path.join(toolsdir, os.pardir, os.pardir)

The above steps fixed the issue for me.


回答 18

我尝试了许多解决方案,但只有一种对我有用,即安装Microsoft Visual Studio 2008 Express C ++。

我用用C编写的Python 2.7模块(yEnc,MS VS还有其他问题)遇到了这个问题。请注意,Python 2.7是使用MS VS 2008版本而非2010构建的!

尽管它是免费的,但由于MS正在推广VS 2010,因此很难找到它。但是,MSDN官方非常直接的链接仍在起作用:请访问https://stackoverflow.com/a/15319069/2227298以获取下载链接。

I tried many solutions but only one worked for me, the install of Microsoft Visual Studio 2008 Express C++.

I got this issue with a Python 2.7 module written in C (yEnc, which has other issues with MS VS). Note that Python 2.7 is built with MS VS 2008 version, not 2010!

Despite the fact it’s free, it is quite hard to find since MS is promoting VS 2010. Still, the MSDN official very direct links are still working: check https://stackoverflow.com/a/15319069/2227298 for download links.


回答 19

如果您已安装mingw

pip install --global-option build_ext --global-option --compiler=mingw32 packagename

起作用,迫使pip使用mingw编译器而不是Microsoft的编译器进行构建。有关详细信息,请参见https://github.com/pypa/pip/issues/18(最新文章)。

If you have mingw installed

pip install --global-option build_ext --global-option --compiler=mingw32 packagename

works, forcing pip to build using the mingw compiler instead of Microsoft’s. See here https://github.com/pypa/pip/issues/18 for details (last post).


回答 20

http://www.microsoft.com/zh-cn/download/details.aspx?id=44266上的 Python 2.7版Microsoft Visual C ++编译器不是解决方案吗?

Is Microsoft Visual C++ Compiler for Python 2.7 at http://www.microsoft.com/en-us/download/details.aspx?id=44266 not a solution?


回答 21

在2016年解决此问题的最简单方法是先安装Chocolatey,然后再安装该 vcpython27软件包。打开Powershell:

> iex ((new-object net.webclient).DownloadString('https://chocolatey.org/install.ps1'))
> choco install python2 -y
> choco install vcpython27 -y

The easiest way to solve this in 2016 is to install Chocolatey and then the vcpython27 package. Open Powershell:

> iex ((new-object net.webclient).DownloadString('https://chocolatey.org/install.ps1'))
> choco install python2 -y
> choco install vcpython27 -y

回答 22

我不知道这是否是为时已晚,但我发现微软的Visual C ++编译器为Python 2.7读取

如果需要此编译器包,您将收到的典型错误消息是找不到vcvarsall.bat

希望这可以帮助!

I don’t know if it is too late, but I found Microsoft Visual C++ Compiler for Python 2.7 which reads

The typical error message you will receive if you need this compiler package is Unable to find vcvarsall.bat

Hope this helps!


回答 23

我遇到了同样的问题,目前已经解决了。

“ Google”告诉我,我需要安装“ Python 2.7的Microsoft Visual C ++编译器”。我不仅安装了该工具,还安装了Visual C ++ 2008 Reditributable,但这并没有帮助。然后,我尝试安装Visual C ++ 2008 Express Edition。问题已经解决了!

只需尝试安装Visual C ++ 2008 Express Edition!

I got the same problem and have solved it at the moment.

“Google” told me that I need to install “Microsoft Visual C++ Compiler for Python 2.7”. I install not only the tool, but also Visual C++ 2008 Reditributable, but it didn’t help. I then tried to install Visual C++ 2008 Express Edition. And the problem has gone!

Just try to install Visual C++ 2008 Express Edition!


回答 24

调用import setuptools将Monkey补丁distutils强制与Visual Studio兼容。vcvars32.bat手动调用将设置虚拟环境,并防止编译器引发其他常见错误。对于VS 2017,文件位于

“ C:\ Program Files(x86)\ Microsoft Visual Studio \ 2017 \ Community \ VC \ Auxiliary \ Build \ vcvars32.bat”

这是我用来快速将.pyx文件编译为.pyd的安装脚本:(注意:它使用第三方模块 send2trash

# cython_setup.py
import sys, os, time, platform, subprocess
from setuptools import setup, find_packages
from Cython.Build import cythonize
from traceback import format_exc

# USAGE:
#
#   from cython_setup import run
#   run(pyx_path)

# vcvars = r"C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Auxiliary\Build\vcvars32.bat"

# NOTE: to use visual studio 2017 you must have setuptools version 34+
vcvars = r"C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\VC\Auxiliary\Build\vcvars32.bat"


def _build_ext():
    try:
        pyx_path = sys.argv.pop(-1)
        pyx_path = os.path.abspath(pyx_path)
        if not os.path.exists(pyx_path):
            raise FileNotFoundError(f"{pyx_path} does not exist")
        project_name = sys.argv.pop(-1)
        os.chdir(os.path.abspath(os.path.dirname(pyx_path)))

        print("cwd: %s" % os.getcwd())
        print(os.path.abspath("build"))
        setup(
            name=project_name,
            # cmdclass = {'build_ext': build_ext},
            packages=find_packages(),
            # ext_modules=cythonize(extensions)
            ext_modules=cythonize(pyx_path,
                                  compiler_directives={'language_level': 3, 'infer_types': True, 'binding': False},
                                  annotate=True),
            # include_dirs = [numpy.get_include()]
            build_dir=os.path.abspath("build")
        )
    except:
        input(format_exc())


def retry(func):
    def wrapper(*args, **kw):
        tries = 0
        while True:
            try:
                return func(*args, **kw)
            except Exception:
                tries += 1
                if tries > 4:
                    raise
                time.sleep(0.4)

    return wrapper


@retry
def cleanup(pyx_path):
    from send2trash import send2trash
    c_file = os.path.splitext(pyx_path)[0] + ".c"
    if os.path.exists(c_file):
        os.remove(c_file)

    if os.path.exists("build"):
        send2trash("build")


def move_pyd_files(pyx_path):
    pyx_dir = os.path.dirname(pyx_path)
    build_dir = os.path.join(pyx_dir, "build")
    if not os.path.exists(build_dir):
        raise RuntimeError(f"build_dir {build_dir} did not exist....")
    found_pyd = False
    for top, dirs, nondirs in os.walk(build_dir):
        for name in nondirs:
            if name.lower().endswith(".pyd") or name.lower().endswith(".so"):
                found_pyd = True
                old_path = os.path.join(top, name)
                new_path = os.path.join(pyx_dir, name)
                if os.path.exists(new_path):
                    print(f"removing {new_path}")
                    os.remove(new_path)
                print(f"file created at {new_path}")
                os.rename(old_path, new_path)
    if not found_pyd:
        raise RuntimeError("Never found .pyd file to move")

def run(pyx_path):
    """
    :param pyx_path:
    :type pyx_path:
    :return: this function creates the batch file, which in turn calls this module, which calls cythonize, once done
    the batch script deletes itself... I'm sure theres a less convoluted way of doing this, but it works
    :rtype:
    """
    try:
        project_name = os.path.splitext(os.path.basename(pyx_path))[0]
        run_script(project_name, os.path.abspath(pyx_path))
    except:
        input(format_exc())


def run_script(project_name, pyx_path):
    dirname = os.path.dirname(pyx_path)
    # ------------------------------
    os.chdir(dirname)
    if os.path.exists(vcvars):
        #  raise RuntimeError(
        # f"Could not find vcvars32.bat at {vcvars}\nis Visual Studio Installed?\nIs setuptools version > 34?")
        subprocess.check_call(f'call "{vcvars}"', shell=True)

    cmd = "python" if platform.system() == "Windows" else "python3"
    subprocess.check_call(f'{cmd} "{__file__}" build_ext "{project_name}" "{pyx_path}"', shell=True)
    move_pyd_files(pyx_path)
    cleanup(pyx_path)


if len(sys.argv) > 2:
    _build_ext()

calling import setuptools will monkey patch distutils to force compatibility with Visual Studio. Calling vcvars32.bat manually will setup the virtual environment and prevent other common errors the compiler will throw. For VS 2017 the file is located at

“C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Auxiliary\Build\vcvars32.bat”

Here is the setup script I use to quickly compile .pyx files to .pyd: (Note: it uses the 3rd party module send2trash

# cython_setup.py
import sys, os, time, platform, subprocess
from setuptools import setup, find_packages
from Cython.Build import cythonize
from traceback import format_exc

# USAGE:
#
#   from cython_setup import run
#   run(pyx_path)

# vcvars = r"C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Auxiliary\Build\vcvars32.bat"

# NOTE: to use visual studio 2017 you must have setuptools version 34+
vcvars = r"C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\VC\Auxiliary\Build\vcvars32.bat"


def _build_ext():
    try:
        pyx_path = sys.argv.pop(-1)
        pyx_path = os.path.abspath(pyx_path)
        if not os.path.exists(pyx_path):
            raise FileNotFoundError(f"{pyx_path} does not exist")
        project_name = sys.argv.pop(-1)
        os.chdir(os.path.abspath(os.path.dirname(pyx_path)))

        print("cwd: %s" % os.getcwd())
        print(os.path.abspath("build"))
        setup(
            name=project_name,
            # cmdclass = {'build_ext': build_ext},
            packages=find_packages(),
            # ext_modules=cythonize(extensions)
            ext_modules=cythonize(pyx_path,
                                  compiler_directives={'language_level': 3, 'infer_types': True, 'binding': False},
                                  annotate=True),
            # include_dirs = [numpy.get_include()]
            build_dir=os.path.abspath("build")
        )
    except:
        input(format_exc())


def retry(func):
    def wrapper(*args, **kw):
        tries = 0
        while True:
            try:
                return func(*args, **kw)
            except Exception:
                tries += 1
                if tries > 4:
                    raise
                time.sleep(0.4)

    return wrapper


@retry
def cleanup(pyx_path):
    from send2trash import send2trash
    c_file = os.path.splitext(pyx_path)[0] + ".c"
    if os.path.exists(c_file):
        os.remove(c_file)

    if os.path.exists("build"):
        send2trash("build")


def move_pyd_files(pyx_path):
    pyx_dir = os.path.dirname(pyx_path)
    build_dir = os.path.join(pyx_dir, "build")
    if not os.path.exists(build_dir):
        raise RuntimeError(f"build_dir {build_dir} did not exist....")
    found_pyd = False
    for top, dirs, nondirs in os.walk(build_dir):
        for name in nondirs:
            if name.lower().endswith(".pyd") or name.lower().endswith(".so"):
                found_pyd = True
                old_path = os.path.join(top, name)
                new_path = os.path.join(pyx_dir, name)
                if os.path.exists(new_path):
                    print(f"removing {new_path}")
                    os.remove(new_path)
                print(f"file created at {new_path}")
                os.rename(old_path, new_path)
    if not found_pyd:
        raise RuntimeError("Never found .pyd file to move")

def run(pyx_path):
    """
    :param pyx_path:
    :type pyx_path:
    :return: this function creates the batch file, which in turn calls this module, which calls cythonize, once done
    the batch script deletes itself... I'm sure theres a less convoluted way of doing this, but it works
    :rtype:
    """
    try:
        project_name = os.path.splitext(os.path.basename(pyx_path))[0]
        run_script(project_name, os.path.abspath(pyx_path))
    except:
        input(format_exc())


def run_script(project_name, pyx_path):
    dirname = os.path.dirname(pyx_path)
    # ------------------------------
    os.chdir(dirname)
    if os.path.exists(vcvars):
        #  raise RuntimeError(
        # f"Could not find vcvars32.bat at {vcvars}\nis Visual Studio Installed?\nIs setuptools version > 34?")
        subprocess.check_call(f'call "{vcvars}"', shell=True)

    cmd = "python" if platform.system() == "Windows" else "python3"
    subprocess.check_call(f'{cmd} "{__file__}" build_ext "{project_name}" "{pyx_path}"', shell=True)
    move_pyd_files(pyx_path)
    cleanup(pyx_path)


if len(sys.argv) > 2:
    _build_ext()

回答 25

使用此链接下载和安装Visual C ++ 2015生成工具。它会自动下载visualcppbuildtools_full.exe并安装Visual C ++ 14.0,而无需实际安装Visual Studio。安装完成后,重试pip安装,您将不会再次收到错误。

我已经在以下平台和版本上对其进行了测试:

Python 3.6 on Windows 7 64-bit
Python 3.7 on Windows Server 2016 (64-bit system)
Python 3.8 on Windows 10 64-bit

Use this link to download and install Visual C++ 2015 Build Tools. It will automatically download visualcppbuildtools_full.exe and install Visual C++ 14.0 without actually installing Visual Studio. After the installation completes, retry pip install and you won’t get the error again.

I have tested it on following platform and versions:

Python 3.6 on Windows 7 64-bit
Python 3.7 on Windows Server 2016 (64-bit system)
Python 3.8 on Windows 10 64-bit

回答 26

如果要在安装Visual Studio 的Windows机器上安装pyodbc,另一个选择是使用二进制发行版手动安装pyodbc。

如果您在使用的计算机上没有管理员特权并尝试设置virtualenv,则此功能特别有用

脚步:

  1. 此处下载最新的Windows安装程序(pyodbc-XXXwin-Y-py2.7.exe)
  2. 使用7-Zip(或WinRAR或其他工具)打开安装程序可执行文件
  3. 提取pyodbc.pyd和pyodbc-XXX-py2.7.egg-info并将它们放在 [python installation directory or virtualenv]\Lib\site-packages
  4. 没有步骤4 :)

If you’re looking to install pyodbc on a Windows box that doesn’t have Visual Studio installed another option is to manually install pyodbc using the binary distribution.

This is particularly useful if you do not have administrator privileges on the machine you’re working with and are trying to set up a virtualenv.

Steps:

  1. Download the latest Windows installer from here (pyodbc-X.X.X.win-Y-py2.7.exe)
  2. Open the installer executable using 7-Zip (or WinRAR or whatever)
  3. Extract pyodbc.pyd and pyodbc-X.X.X-py2.7.egg-info and place them in [python installation directory or virtualenv]\Lib\site-packages
  4. There is no step 4 :)

回答 27

使用Python 3.4,依赖关系依赖于Visual Studio2010。安装Visual C ++ 2010 Express对我来说解决了这个问题。

欺骗我使用我碰巧无法使用的VS 2008或2013安装。

With Python 3.4, the dependency is on Visual Studio 2010. Installing Visual C++ 2010 Express fixed the problem for me.

Tricking it into using the VS 2008 or 2013 installs that I happened to have didn’t work.


回答 28

您可以使用easy_install代替pip,它对我有用。

You can use easy_install instead of pip it works for me.


回答 29

@monkey给出的答案是正确的答案之一,但不完整。

如果您想使用MinGW,则应该选择C,C ++以及在MinGW安装过程中建议的其他开发工具,以获取“ make.exe”。

您还必须在环境中将路径设置为make.exe。

要完成他的回答,请按以下步骤操作:

  1. 将mingw32的bin目录添加到您的环境变量中
  2. 附加 C:\Programs\MinGW\bin;C:\Programs\MinGW\msys\1.0\bin;到PATH
  3. 编辑distutils.cfg位于以下位置的文件(如果不存在则创建)C:\Python26\Lib\distutils\distutils.cfg

    [build]
    compiler=mingw32

通过打开新的cmd.exe确保设置了环境变量。

The answer given by @monkey is one of the correct ones, but it is incomplete.

In case you’d like to use MinGW, you should select the C, C++ and also other development tools suggested during the MinGW installation process to also get “make.exe.”

You must also have the path set to make.exe in the env.

To complete his answer, here are the steps:

  1. Add mingw32’s bin directory to your environment variables
  2. Append C:\Programs\MinGW\bin;C:\Programs\MinGW\msys\1.0\bin; to the PATH
  3. Edit (create if it doesn’t exist) the distutils.cfg file located at C:\Python26\Lib\distutils\distutils.cfg to be:

    [build]
    compiler=mingw32
    

Make sure the environment variables is set by opening a new cmd.exe.


python setup.py卸载

问题:python setup.py卸载

我已经使用安装了python软件包python setup.py install

如何卸载?

I have installed a python package with python setup.py install.

How do I uninstall it?


回答 0

注意:避免python setup.py install使用pip install .

您需要手动删除所有文件,还需要撤消安装过程中手动执行的任何其他操作。

如果您不知道所有文件的列表,则可以使用--record选件重新安装它,然后查看生成的列表。

要记录已安装文件的列表,可以使用:

python setup.py install --record files.txt

想要卸载后,可以使用xargs进行删除:

xargs rm -rf < files.txt

或者,如果您正在运行Windows,请使用Powershell:

Get-Content files.txt | ForEach-Object {Remove-Item $_ -Recurse -Force}

然后也删除包含的目录,例如/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/my_module-0.1.egg/on macOS。它没有文件,但是Python仍将导入一个空模块:

>>> import my_module
>>> my_module.__file__
None

删除后,Python将显示:

>>> import my_module
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'my_module'

Note: Avoid using python setup.py install use pip install .

You need to remove all files manually, and also undo any other stuff that installation did manually.

If you don’t know the list of all files, you can reinstall it with the --record option, and take a look at the list this produces.

To record a list of installed files, you can use:

python setup.py install --record files.txt

Once you want to uninstall you can use xargs to do the removal:

xargs rm -rf < files.txt

Or if you’re running Windows, use Powershell:

Get-Content files.txt | ForEach-Object {Remove-Item $_ -Recurse -Force}

Then delete also the containing directory, e.g. /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/my_module-0.1.egg/ on macOS. It has no files, but Python will still import an empty module:

>>> import my_module
>>> my_module.__file__
None

Once deleted, Python shows:

>>> import my_module
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'my_module'

回答 1

对我来说,以下主要工作方式:

已安装点子,例如:

$ easy_install pip

从pip的角度检查已安装的软件包的名称:

$ pip freeze

这将列出您已经安装(并且被pip检测到)的所有软件包的名称。该名称可能会很长,然后仅使用和之后显示的程序包的名称#egg=。在大多数情况下,您也可以忽略版本部分(无论是后面的==还是-)。

然后卸载该软件包:

$ pip uninstall package.name.you.have.found

如果它要求您确认删除软件包,那么您很幸运,它将被删除。

pip应检测所有由pip安装的软件包。它还应检测通过easy_install或setup.py安装的大多数软件包,但这在极少数情况下可能会失败。

这是来自本地测试的真实示例,带有ttr.rdstmc在Windows上命名的软件包。

$ pip freeze |grep ttr
ttr.aws.s3==0.1.1dev
ttr.aws.utils.s3==0.3.0
ttr.utcutils==0.1.1dev

$ python setup.py develop
.....
.....
Finished processing dependencies for ttr.rdstmc==0.0.1dev

$ pip freeze |grep ttr
ttr.aws.s3==0.1.1dev
ttr.aws.utils.s3==0.3.0
-e hg+https://vlcinsky@bitbucket.org/vlcinsky/ttr.rdstmc@d61a9922920c508862602f7f39e496f7b99315f0#egg=ttr.rdstmc-dev
ttr.utcutils==0.1.1dev

$ pip uninstall ttr.rdstmc
Uninstalling ttr.rdstmc:
  c:\python27\lib\site-packages\ttr.rdstmc.egg-link
Proceed (y/n)? y
  Successfully uninstalled ttr.rdstmc

$ pip freeze |grep ttr
ttr.aws.s3==0.1.1dev
ttr.aws.utils.s3==0.3.0
ttr.utcutils==0.1.1dev

编辑2015-05-20

上面写的所有内容仍然适用,无论如何,现在有一些小的修改。

在python 2.7.9和python 3.4中安装pip

最新的python版本附带了一个软件包ensurepip,即使离线也可以安装pip:

$ python -m surepip-升级

在某些系统(例如Debian Jessie)上,此功能不可用(以防止破坏系统python安装)。

使用grepfind

上面的示例假定您已grep安装。我(当时我的计算机上装有MS Windows)安装了一套Linux实用程序(包括grep)。或者,使用本机MS Windows find或简单地忽略该过滤,并在更长的检测到的python软件包列表中找到名称。

For me, the following mostly works:

have pip installed, e.g.:

$ easy_install pip

Check, how is your installed package named from pip point of view:

$ pip freeze

This shall list names of all packages, you have installed (and which were detected by pip). The name can be sometime long, then use just the name of the package being shown at the and after #egg=. You can also in most cases ignore the version part (whatever follows == or -).

Then uninstall the package:

$ pip uninstall package.name.you.have.found

If it asks for confirmation about removing the package, then you are lucky guy and it will be removed.

pip shall detect all packages, which were installed by pip. It shall also detect most of the packages installed via easy_install or setup.py, but this may in some rare cases fail.

Here is real sample from my local test with package named ttr.rdstmc on MS Windows.

$ pip freeze |grep ttr
ttr.aws.s3==0.1.1dev
ttr.aws.utils.s3==0.3.0
ttr.utcutils==0.1.1dev

$ python setup.py develop
.....
.....
Finished processing dependencies for ttr.rdstmc==0.0.1dev

$ pip freeze |grep ttr
ttr.aws.s3==0.1.1dev
ttr.aws.utils.s3==0.3.0
-e hg+https://vlcinsky@bitbucket.org/vlcinsky/ttr.rdstmc@d61a9922920c508862602f7f39e496f7b99315f0#egg=ttr.rdstmc-dev
ttr.utcutils==0.1.1dev

$ pip uninstall ttr.rdstmc
Uninstalling ttr.rdstmc:
  c:\python27\lib\site-packages\ttr.rdstmc.egg-link
Proceed (y/n)? y
  Successfully uninstalled ttr.rdstmc

$ pip freeze |grep ttr
ttr.aws.s3==0.1.1dev
ttr.aws.utils.s3==0.3.0
ttr.utcutils==0.1.1dev

Edit 2015-05-20

All what is written above still applies, anyway, there are small modifications available now.

Install pip in python 2.7.9 and python 3.4

Recent python versions come with a package ensurepip allowing to install pip even when being offline:

$ python -m ensurepip –upgrade

On some systems (like Debian Jessie) this is not available (to prevent breaking system python installation).

Using grep or find

Examples above assume, you have grep installed. I had (at the time I had MS Windows on my machine) installed set of linux utilities (incl. grep). Alternatively, use native MS Windows find or simply ignore that filtering and find the name in a bit longer list of detected python packages.


回答 2

第一个答案有问题:

  • 在Mac上无法使用。
  • 如果安装的文件包含空格或其他特殊字符,该xargs命令将失败,并删除与各个单词匹配的所有文件/目录。
  • -rrm -rf是不必要的,在最坏的情况可能会删除你不想要的东西。

相反,对于类Unix:

sudo python setup.py install --record files.txt
# inspect files.txt to make sure it looks ok. Then:
tr '\n' '\0' < files.txt | xargs -0 sudo rm -f --

对于Windows:

python setup.py bdist_wininst
dist/foo-1.0.win32.exe

卸载setup.py安装还有一些无法解决的问题,在典型情况下不会打扰您。有关更完整的答案,请参见以下Wiki页面:

https://ofswiki.org/wiki/Uninstalling_setup.py_install

The #1 answer has problems:

  • Won’t work on mac.
  • If a file is installed which includes spaces or other special characters, the xargs command will fail, and delete any files/directories which matched the individual words.
  • the -r in rm -rf is unnecessary and at worst could delete things you don’t want to.

Instead, for unix-like:

sudo python setup.py install --record files.txt
# inspect files.txt to make sure it looks ok. Then:
tr '\n' '\0' < files.txt | xargs -0 sudo rm -f --

And for windows:

python setup.py bdist_wininst
dist/foo-1.0.win32.exe

There are also unsolvable problems with uninstalling setup.py install which won’t bother you in a typical case. For a more complete answer, see this wiki page:

https://ofswiki.org/wiki/Uninstalling_setup.py_install


回答 3

首先记录您已安装的文件。即使您先前已经运行过,也可以重复此命令setup.py install

python setup.py install --record files.txt

要卸载时,您可以:

sudo rm $(cat files.txt)

之所以可行,是因为rm命令使用空格分隔的文件列表来删除,并且您的安装记录就是这样的列表。

First record the files you have installed. You can repeat this command, even if you have previously run setup.py install:

python setup.py install --record files.txt

When you want to uninstall you can just:

sudo rm $(cat files.txt)

This works because the rm command takes a whitespace-seperated list of files to delete and your installation record is just such a list.


回答 4

现在,python让您可以选择在安装pip过程中进行安装(我在Windows上,至少python在Windows上可以!)。考虑到您已选择pip在安装python时进行安装(实际上是默认设置,因此不必选择),pip已经为您安装了。然后,pip在命令提示符下键入,您应该会看到一个帮助。您可以在此处找到必要的使用说明。例如,pip list显示已安装软件包的列表。您可以使用

pip uninstall package_name

卸载不再需要的任何软件包。在此处阅读更多信息(pip文档)

Now python gives you the choice to install pip during the installation (I am on Windows, and at least python does so for Windows!). Considering you had chosen to install pip during installation of python (you don’t actually have to choose because it is default), pip is already installed for you. Then, type in pip in command prompt, you should see a help come up. You can find necessary usage instructions there. E.g. pip list shows you the list of installed packages. You can use

pip uninstall package_name

to uninstall any package that you don’t want anymore. Read more here (pip documentation).


回答 5

懒惰的方式:只需从Windows安装菜单(如果使用Windows)或从rpm命令卸载,前提是您在创建分发程序包后首先重新安装它。

例如,

python setup.py bdist_wininst
dist/foo-1.0.win32.exe

(“ foo”当然是示例)。

The lazy way: simply uninstall from the Windows installation menu (if you’re using Windows), or from the rpm command, provided you first re-install it after creating a distribution package.

For example,

python setup.py bdist_wininst
dist/foo-1.0.win32.exe

(“foo” being an example of course).


回答 6

转到python软件包目录并删除.egg文件,例如:在python 2.5(ubuntu)中:/usr/lib/python2.5/site-packages/

在python 2.6(ubuntu)中:/usr/local/lib/python2.6/dist-packages/

Go to your python package directory and remove your .egg file, e.g.: In python 2.5(ubuntu): /usr/lib/python2.5/site-packages/

In python 2.6(ubuntu): /usr/local/lib/python2.6/dist-packages/


回答 7

不能完全回答问题,但每天都能对我有所帮助:

安装您的软件包

pip install .

这会将包装放入$HOME/.local。卸载

pip uninstall <package_name>

Not exactly answering the question, but something that helps me every day:

Install your packages with

pip install .

This puts the package in $HOME/.local. Uninstall with

pip uninstall <package_name>

回答 8

可能您可以这样做:

1)获取python版本-

[linux machine]# python
Python 2.4.3 (#1, Jun 18 2012, 14:38:55) 

->上面的命令为您提供了当前的python版本2.4.3

2)获取python的安装目录-

[linux machine]# whereis python
python: /usr/bin/python /usr/bin/python2.4 /usr/lib/python2.4 /usr/local/bin/python2.5 /usr/include/python2.4 /usr/share/man/man1/python.1.gz

->从上面的命令中,您可以获得安装目录-/ usr/lib/python2.4/sitepackages

3)从这里您可以删除软件包和python egg文件

[linux machine]# cd /usr/lib/python2.4/site-packages
[linux machine]# rm -rf paramiko-1.12.0-py2.4.egg paramiko-1.7.7.1-py2.4.egg paramiko-1.9.0-py2.4.egg

这对我有用。而且我能够卸载困扰我的软件包:)

Probably you can do this as an alternative :-

1) Get the python version –

[linux machine]# python
Python 2.4.3 (#1, Jun 18 2012, 14:38:55) 

-> The above command gives you the current python Version which is 2.4.3

2) Get the installation directory of python –

[linux machine]# whereis python
python: /usr/bin/python /usr/bin/python2.4 /usr/lib/python2.4 /usr/local/bin/python2.5 /usr/include/python2.4 /usr/share/man/man1/python.1.gz

-> From above command you can get the installation directory which is – /usr/lib/python2.4/site-packages

3) From here you can remove the packages and python egg files

[linux machine]# cd /usr/lib/python2.4/site-packages
[linux machine]# rm -rf paramiko-1.12.0-py2.4.egg paramiko-1.7.7.1-py2.4.egg paramiko-1.9.0-py2.4.egg

This worked for me.. And i was able to uninstall package which was troubling me :)


回答 9

我认为您可以打开setup.py,找到软件包名称,然后要求pip卸载它。

假设名称在“ METADATA”变量中可用:

pip uninstall $(python -c "from setup import METADATA; print METADATA['name']")

I think you can open the setup.py, locate the package name, and then ask pip to uninstall it.

Assuming the name is available in a ‘METADATA’ variable:

pip uninstall $(python -c "from setup import METADATA; print METADATA['name']")

回答 10

扩展一下Martin所说的内容,记录安装输出和一些bash脚本就可以很好地解决问题。这是我的工作

for i in $(less install.record);
sudo rm $i;
done;

和presto。已卸载。

Extending on what Martin said, recording the install output and a little bash scripting does the trick quite nicely. Here’s what I do…

for i in $(less install.record);
sudo rm $i;
done;

And presto. Uninstalled.


回答 11

如果在重新安装软件包后仍有一些文件应删除,请确保该文件夹build也已删除。因此,假设这pkg是您要删除的软件包:

rm -r $(python3 -c "import pkg; print(pkg.__path__[0] + '*' )") 
rm -rf build

以上为python3计算并删除了软件包及其* .egg-info文件

If you still have files that are supposed to be deleted after re-installing a package, make sure the folder build is also deleted. Therefore, assuming that pkg is the package you want to delete:

rm -r $(python3 -c "import pkg; print(pkg.__path__[0] + '*' )") 
rm -rf build

Obove work out for python3 and delete the package and its *.egg-info file


回答 12

{virtualenv}/lib/python2.7/site-packages/(如果未使用virtualenv,则为{system_dir}/lib/python2.7/dist-packages/

  • 删除鸡蛋文件(例如distribute-0.6.34-py2.7.egg
  • 如果文件中有任何内容easy-install.pth,请删除相应的行(它应该是源目录或egg文件的路径)。

At {virtualenv}/lib/python2.7/site-packages/ (if not using virtualenv then {system_dir}/lib/python2.7/dist-packages/)

  • Remove the egg file (e.g. distribute-0.6.34-py2.7.egg)
  • If there is any from file easy-install.pth, remove the corresponding line (it should be a path to the source directory or of an egg file).

回答 13

我过去曾经在全局环境中偶然运行过“ python setup.py install”,并且卸载时遇到很多困难。这些解决方案没有帮助。“ pip卸载”不适用于“无法卸载’splunk-appinspect’。找不到要卸载的文件。” “ sudo pip卸载”不起作用“无法卸载要求splunk-appinspect,未安装”。我尝试卸载pip,删除pip缓存,在硬盘上搜索该软件包等,…

“ pip show”最终将我引向解决方案,“ Location:”指向目录,并且重命名该目录导致打包的内容从pip列表中删除。我重命名了目录,但它没有重新出现在pip的列表中,现在我可以在virtualenv中重新安装我的软件包了。

I had run “python setup.py install” at some point in the past accidentally in my global environment, and had much difficulty uninstalling. These solutions didn’t help. “pip uninstall ” didn’t work with “Can’t uninstall ‘splunk-appinspect’. No files were found to uninstall.” “sudo pip uninstall ” didn’t work “Cannot uninstall requirement splunk-appinspect, not installed”. I tried uninstalling pip, deleting the pip cache, searching my hard drive for the package, etc…

“pip show ” eventually led me to the solution, the “Location:” was pointing to a directory, and renaming that directory caused the packaged to be removed from pip’s list. I renamed the directory back, and it didn’t reappear in pip’s list, and now I can reinstall my package in a virtualenv.


回答 14

python setup.py install在PyCharm中运行了一次,它将所有软件包安装到conda基本环境中。以后,当我要删除所有这些程序包时,将pip uninstall无法正常工作。我不得不从/anaconda3/lib/python3.7/site-packages中手动删除它们:(

因此,我看不出他们为什么使用setup.py而不是编写requirements.txt文件的原因。需求文件可用于在虚拟环境中安装软件包,并且不会与系统python软件包混淆。

I had run python setup.py install once in my PyCharm, it installs all the packages into my conda base environment. Later when I want to remove all these packages, pip uninstall does not work. I had to delete them from /anaconda3/lib/python3.7/site-packages manually :(

So I don’t see the reason why they use setup.py instead of writing requirements.txt file. The requirement file can be used to install packages in virtual environment and won’t mess with system python packages.


回答 15

最好使用bash读取命令来删除相关文件,如下所示:

sudo python setup.py install --record files.txt
sudo bash -c "cat files.txt | xargs rm -rf"

It might be better to remove related files by using bash to read commands, like the following:

sudo python setup.py install --record files.txt
sudo bash -c "cat files.txt | xargs rm -rf"

什么是setup.py?

问题:什么是setup.py?

谁能解释一下setup.py它是什么以及如何进行配置或使用?

Can anyone please explain what setup.py is and how it can be configured or used?


回答 0

setup.py 是一个python文件,通常会告诉您要安装的模块/软件包已与Distutils打包并分发,Distutils是分发Python模块的标准。

这使您可以轻松安装Python软件包。通常写就足够了:

$ pip install . 

pip将使用setup.py安装模块。避免setup.py直接调用。

https://docs.python.org/3/installing/index.html#installing-index

setup.py is a python file, which usually tells you that the module/package you are about to install has been packaged and distributed with Distutils, which is the standard for distributing Python Modules.

This allows you to easily install Python packages. Often it’s enough to write:

$ pip install . 

pip will use setup.py to install your module. Avoid calling setup.py directly.

https://docs.python.org/3/installing/index.html#installing-index


回答 1

它有助于foo在您的计算机上安装python软件包(也可以位于中virtualenv),以便您可以foo从其他项目以及[I] Python提示符中导入该软件包。

它完成pipeasy_install等的类似工作,


使用 setup.py

让我们从一些定义开始:

-包含__init__.py文件的文件夹/目录。
模块 -具有.py扩展名的有效python文件。
分发 -一个软件包与其他软件包模块的关系

假设您要安装名为的软件包foo。那你做

$ git clone https://github.com/user/foo  
$ cd foo
$ python setup.py install

相反,如果您不想实际安装它,但仍然想使用它。然后做,

$ python setup.py develop  

此命令将在站点包内创建到源目录的符号链接,而不是复制内容。因此,它非常快(特别是对于大包装)。


创造 setup.py

如果您有类似的打包树,

foo
├── foo
   ├── data_struct.py
   ├── __init__.py
   └── internals.py
├── README
├── requirements.txt
└── setup.py

然后,在setup.py脚本中执行以下操作,以便可以将其安装在某些计算机上:

from setuptools import setup

setup(
   name='foo',
   version='1.0',
   description='A useful module',
   author='Man Foo',
   author_email='foomail@foo.com',
   packages=['foo'],  #same as name
   install_requires=['bar', 'greek'], #external packages as dependencies
)

相反,如果您的程序包树更复杂,如以下所示:

foo
├── foo
   ├── data_struct.py
   ├── __init__.py
   └── internals.py
├── README
├── requirements.txt
├── scripts
   ├── cool
   └── skype
└── setup.py

然后,setup.py在这种情况下,您将像:

from setuptools import setup

setup(
   name='foo',
   version='1.0',
   description='A useful module',
   author='Man Foo',
   author_email='foomail@foo.com',
   packages=['foo'],  #same as name
   install_requires=['bar', 'greek'], #external packages as dependencies
   scripts=[
            'scripts/cool',
            'scripts/skype',
           ]
)

向(setup.py)添加更多内容,并使其得体:

from setuptools import setup

with open("README", 'r') as f:
    long_description = f.read()

setup(
   name='foo',
   version='1.0',
   description='A useful module',
   license="MIT",
   long_description=long_description,
   author='Man Foo',
   author_email='foomail@foo.com',
   url="http://www.foopackage.com/",
   packages=['foo'],  #same as name
   install_requires=['bar', 'greek'], #external packages as dependencies
   scripts=[
            'scripts/cool',
            'scripts/skype',
           ]
)

long_description被使用pypi.org作为你的包的README描述。


最后,您现在可以将软件包上传到PyPi.org,以便其他人可以使用来安装您的软件包pip install yourpackage

第一步是使用以下方法在pypi中声明您的软件包名称和空间:

$ python setup.py register

注册您的包裹名称后,任何人都无法声明或使用它。成功注册后,您必须通过以下方式将软件包上传到云(到云):

$ python setup.py upload

您也可以选择GPG通过以下方式对包裹进行签名:

$ python setup.py --sign upload

奖励setup.py在此处查看来自真实项目的示例:torchvision-setup.py

It helps to install a python package foo on your machine (can also be in virtualenv) so that you can import the package foo from other projects and also from [I]Python prompts.

It does the similar job of pip, easy_install etc.,


Using setup.py

Let’s start with some definitions:

Package – A folder/directory that contains __init__.py file.
Module – A valid python file with .py extension.
Distribution – How one package relates to other packages and modules.

Let’s say you want to install a package named foo. Then you do,

$ git clone https://github.com/user/foo  
$ cd foo
$ python setup.py install

Instead, if you don’t want to actually install it but still would like to use it. Then do,

$ python setup.py develop  

This command will create symlinks to the source directory within site-packages instead of copying things. Because of this, it is quite fast (particularly for large packages).


Creating setup.py

If you have your package tree like,

foo
├── foo
│   ├── data_struct.py
│   ├── __init__.py
│   └── internals.py
├── README
├── requirements.txt
└── setup.py

Then, you do the following in your setup.py script so that it can be installed on some machine:

from setuptools import setup

setup(
   name='foo',
   version='1.0',
   description='A useful module',
   author='Man Foo',
   author_email='foomail@foo.com',
   packages=['foo'],  #same as name
   install_requires=['bar', 'greek'], #external packages as dependencies
)

Instead, if your package tree is more complex like the one below:

foo
├── foo
│   ├── data_struct.py
│   ├── __init__.py
│   └── internals.py
├── README
├── requirements.txt
├── scripts
│   ├── cool
│   └── skype
└── setup.py

Then, your setup.py in this case would be like:

from setuptools import setup

setup(
   name='foo',
   version='1.0',
   description='A useful module',
   author='Man Foo',
   author_email='foomail@foo.com',
   packages=['foo'],  #same as name
   install_requires=['bar', 'greek'], #external packages as dependencies
   scripts=[
            'scripts/cool',
            'scripts/skype',
           ]
)

Add more stuff to (setup.py) & make it decent:

from setuptools import setup

with open("README", 'r') as f:
    long_description = f.read()

setup(
   name='foo',
   version='1.0',
   description='A useful module',
   license="MIT",
   long_description=long_description,
   author='Man Foo',
   author_email='foomail@foo.com',
   url="http://www.foopackage.com/",
   packages=['foo'],  #same as name
   install_requires=['bar', 'greek'], #external packages as dependencies
   scripts=[
            'scripts/cool',
            'scripts/skype',
           ]
)

The long_description is used in pypi.org as the README description of your package.


And finally, you’re now ready to upload your package to PyPi.org so that others can install your package using pip install yourpackage.

First step is to claim your package name & space in pypi using:

$ python setup.py register

Once your package name is registered, nobody can claim or use it. After successful registration, you have to upload your package there (to the cloud) by,

$ python setup.py upload

Optionally, you can also sign your package with GPG by,

$ python setup.py --sign upload

Bonus: See a sample setup.py from a real project here: torchvision-setup.py


回答 2

setup.py是Python对多平台安装程序和make文件的解答。

如果您熟悉命令行安装,请make && make install转换为python setup.py build && python setup.py install

一些软件包是纯Python,并且仅按字节编译。其他可能包含本机代码,这将需要本机编译器(如gcccl)和Python接口模块(如swigpyrex)。

setup.py is Python’s answer to a multi-platform installer and make file.

If you’re familiar with command line installations, then make && make install translates to python setup.py build && python setup.py install.

Some packages are pure Python, and are only byte compiled. Others may contain native code, which will require a native compiler (like gcc or cl) and a Python interfacing module (like swig or pyrex).


回答 3

如果您下载的软件包在根文件夹中具有“ setup.py”,则可以通过运行以下命令进行安装

python setup.py install

如果您正在开发项目,并且想知道此文件的用途,请查看有关编写安装脚本的Python文档。

If you downloaded package that has “setup.py” in root folder, you can install it by running

python setup.py install

If you are developing a project and are wondering what this file is useful for, check Python documentation on writing the Setup Script


回答 4

setup.py是通常用该语言编写的库或程序随附的Python脚本。目的是正确安装软件。

许多软件包将distutils框架与结合使用setup.py

http://docs.python.org/distutils/

setup.py is a Python script that is usually shipped with libraries or programs, written in that language. It’s purpose is the correct installation of the software.

Many packages use the distutils framework in conjuction with setup.py.

http://docs.python.org/distutils/


回答 5

setup.py可以在两种情况下使用:首先,您要安装Python软件包。其次,您要创建自己的Python包。通常,标准的Python软件包具有几个重要文件,例如setup.py,setup.cfg和Manifest.in。当您创建Python软件包时,这三个文件将确定(egg-info文件夹下PKG-INFO中的内容)名称,版本,描述,其他所需的安装(通常在.txt文件中)以及其他几个参数。创建包时setup.py将读取setup.cfg(可以是tar.gz)。在Manifest.in中,您可以定义应包含在软件包中的内容。无论如何,您都可以使用setup.py做很多事情,例如

python setup.py build
python setup.py install
python setup.py sdist <distname> upload [-r urltorepo]  (to upload package to pypi or local repo)

还有许多其他命令可以与setup.py一起使用。求助

python setup.py --help-commands

setup.py can be used in two scenarios , First, you want to install a Python package. Second, you want to create your own Python package. Usually standard Python package has couple of important files like setup.py, setup.cfg and Manifest.in. When you are creating the Python package, these three files will determine the (content in PKG-INFO under egg-info folder) name, version, description, other required installations (usually in .txt file) and few other parameters. setup.cfg is read by setup.py while package is created (could be tar.gz ). Manifest.in is where you can define what should be included in your package. Anyways you can do bunch of stuff using setup.py like

python setup.py build
python setup.py install
python setup.py sdist <distname> upload [-r urltorepo]  (to upload package to pypi or local repo)

There are bunch of other commands which could be used with setup.py . for help

python setup.py --help-commands

回答 6

当您通过setup.py打开终端(Mac,Linux)或命令提示符(Windows)下载软件包时。使用“ cd Tab”按钮并为您提供帮助,将路径设置为已下载文件的文件夹的正确位置,该文​​件夹位于setup.py

iMac:~ user $ cd path/pakagefolderwithsetupfile/

按Enter键,您应该会看到类似以下内容:

iMac:pakagefolderwithsetupfile user$

然后输入以下内容python setup.py install

iMac:pakagefolderwithsetupfile user$ python setup.py install

enter。做完了!

When you download a package with setup.py open your Terminal (Mac,Linux) or Command Prompt (Windows). Using cd and helping you with Tab button set the path right to the folder where you have downloaded the file and where there is setup.py :

iMac:~ user $ cd path/pakagefolderwithsetupfile/

Press enter, you should see something like this:

iMac:pakagefolderwithsetupfile user$

Then type after this python setup.py install :

iMac:pakagefolderwithsetupfile user$ python setup.py install

Press enter. Done!


回答 7

要安装已下载的Python软件包,请提取档案并在其中运行setup.py脚本:

python setup.py install

对我来说,这一直很奇怪。将包管理器指向下载位置会更自然,例如在Ruby和Nodejs中。gem install rails-4.1.1.gem

包管理器也更舒适,因为它既熟悉又可靠。另一方面,每个setup.py都是新颖的,因为它是特定于包装的。它要求遵守约定“我相信此setup.py会接受与过去使用的命令相同的命令”。这是对精神意志力的遗憾。

我并不是说setup.py工作流的安全性不如包管理器(我知道Pip只是在内部运行setup.py),但是我肯定觉得这很麻烦。将所有命令都发送到同一个程序包管理器应用程序是一种和谐。您甚至可能会喜欢它。

To install a Python package you’ve downloaded, you extract the archive and run the setup.py script inside:

python setup.py install

To me, this has always felt odd. It would be more natural to point a package manager at the download, as one would do in Ruby and Nodejs, eg. gem install rails-4.1.1.gem

A package manager is more comfortable too, because it’s familiar and reliable. On the other hand, each setup.py is novel, because it’s specific to the package. It demands faith in convention “I trust this setup.py takes the same commands as others I have used in the past”. That’s a regrettable tax on mental willpower.

I’m not saying the setup.py workflow is less secure than a package manager (I understand Pip just runs the setup.py inside), but certainly I feel it’s awkard and jarring. There’s a harmony to commands all being to the same package manager application. You might even grow fond it.


回答 8

setup.py是与其他文件一样的Python文件。它可以采用任何名称,除非按惯例命名,否则setup.py每个脚本都没有不同的过程。

最常setup.py用于安装Python模块,但用于服务器其他目的:

模块:

也许这是setup.py模块中最著名的用法。尽管可以使用来安装它们pip,但pip默认情况下不包括旧的Python版本,因此需要单独安装。

如果您想安装模块但不想安装pip,则唯一的选择是从setup.py文件安装模块。这可以通过完成python setup.py install。这将Python模块安装到根字典(不pipeasy_installECT)。

pip失败时通常使用此方法。例如,如果所需软件包的正确Python版本pip由于可能由于不再维护而无法提供,则下载源并运行python setup.py install将执行相同的操作,除非需要编译的二进制文件(但将忽略编译的二进制文件)。 Python版本-除非返回错误)。

的另一种用法setup.py是从源代码安装软件包。如果模块仍在开发中,则将无法使用wheel文件,并且唯一的安装方法是直接从源代码进行安装。

构建Python扩展:

构建模块后,可以使用distutils安装脚本将其转换为可分发的模块。一旦构建完成,就可以使用上面的命令进行安装。

安装脚本易于构建,一旦文件已正确配置并且可以通过运行进行编译python setup.py build(请参阅所有命令的链接)。

再次setup.py按易用性和惯例命名,但可以使用任何名称。

Cython:

setup.py文件的另一种著名用法包括编译后的扩展名。这些需要具有用户定义值的安装脚本。它们允许快速执行(但一旦编译则依赖平台)。这是文档中的一个简单示例:

from distutils.core import setup
from Cython.Build import cythonize

setup(
    name = 'Hello world app',
    ext_modules = cythonize("hello.pyx"),
)

这可以通过编译 python setup.py build

Cx_Freeze:

需要安装脚本的另一个模块是cx_Freeze。这会将Python脚本转换为可执行文件。这允许包括描述,名称,图标,包在内的许多命令包括,排除等,并且一旦运行将产生可分发的应用程序。文档中的示例:

import sys
from cx_Freeze import setup, Executable
build_exe_options = {"packages": ["os"], "excludes": ["tkinter"]} 

base = None
if sys.platform == "win32":
    base = "Win32GUI"

setup(  name = "guifoo",
        version = "0.1",
        description = "My GUI application!",
        options = {"build_exe": build_exe_options},
        executables = [Executable("guifoo.py", base=base)])

可以通过编译python setup.py build

那么什么是setup.py文件?

很简单,它是一个在Python环境中构建或配置某些东西的脚本。

分发时,程序包应仅包含一个安装脚本,但将多个脚本组合成一个安装脚本并不少见。请注意,这经常涉及distutils但并非总是如此(如我在上一个示例中所示)。要记住的事情是以某种方式配置Python包/脚本。

它使用名称,因此在构建或安装时始终可以使用相同的命令。

setup.py is a Python file like any other. It can take any name, except by convention it is named setup.py so that there is not a different procedure with each script.

Most frequently setup.py is used to install a Python module but server other purposes:

Modules:

Perhaps this is most famous usage of setup.py is in modules. Although they can be installed using pip, old Python versions did not include pip by default and they needed to be installed separately.

If you wanted to install a module but did not want to install pip, just about the only alternative was to install the module from setup.py file. This could be achieved via python setup.py install. This would install the Python module to the root dictionary (without pip, easy_install ect).

This method is often used when pip will fail. For example if the correct Python version of the desired package is not available via pipperhaps because it is no longer maintained, , downloading the source and running python setup.py install would perform the same thing, except in the case of compiled binaries are required, (but will disregard the Python version -unless an error is returned).

Another use of setup.py is to install a package from source. If a module is still under development the wheel files will not be available and the only way to install is to install from the source directly.

Building Python extensions:

When a module has been built it can be converted into module ready for distribution using a distutils setup script. Once built these can be installed using the command above.

A setup script is easy to build and once the file has been properly configured and can be compiled by running python setup.py build (see link for all commands).

Once again it is named setup.py for ease of use and by convention, but can take any name.

Cython:

Another famous use of setup.py files include compiled extensions. These require a setup script with user defined values. They allow fast (but once compiled are platform dependant) execution. Here is a simple example from the documentation:

from distutils.core import setup
from Cython.Build import cythonize

setup(
    name = 'Hello world app',
    ext_modules = cythonize("hello.pyx"),
)

This can be compiled via python setup.py build

Cx_Freeze:

Another module requiring a setup script is cx_Freeze. This converts Python script to executables. This allows many commands such as descriptions, names, icons, packages to include, exclude ect and once run will produce a distributable application. An example from the documentation:

import sys
from cx_Freeze import setup, Executable
build_exe_options = {"packages": ["os"], "excludes": ["tkinter"]} 

base = None
if sys.platform == "win32":
    base = "Win32GUI"

setup(  name = "guifoo",
        version = "0.1",
        description = "My GUI application!",
        options = {"build_exe": build_exe_options},
        executables = [Executable("guifoo.py", base=base)])

This can be compiled via python setup.py build.

So what is a setup.py file?

Quite simply it is a script that builds or configures something in the Python environment.

A package when distributed should contain only one setup script but it is not uncommon to combine several together into a single setup script. Notice this often involves distutils but not always (as I showed in my last example). The thing to remember it just configures Python package/script in some way.

It takes the name so the same command can always be used when building or installing.


回答 9

为简单起见,setup.py的运行就像"__main__"您在调用安装函数时提到的其他答案一样。在setup.py内部,应该放置安装软件包所需的一切。

常用的setup.py功能

以下两节讨论了许多setup.py模块具有的两件事。

setuptools.setup

此功能允许您指定项目属性,例如项目的名称,版本。…最重要的是,如果其他功能打包正确,此功能将允许您安装其他功能。请参阅此网页以获取setuptools.setup的示例。setuptools.setup的

这些属性允许安装以下类型的软件包:

自定义功能

在理想的世界中,setuptools.setup将为您处理所有事情。不幸的是,情况并非总是如此。有时,您需要做一些特定的事情,例如使用subprocess命令安装依赖项,以使要安装的系统处于正确的软件包状态。尝试避免这种情况,这些功能会造成混乱,并且在OS甚至发行版之间通常会有所不同。

To make it simple, setup.py is run as "__main__" when you call the install functions the other answers mentioned. Inside setup.py, you should put everything needed to install your package.

Common setup.py functions

The following two sections discuss two things many setup.py modules have.

setuptools.setup

This function allows you to specify project attributes like the name of the project, the version…. Most importantly, this function allows you to install other functions if they’re packaged properly. See this webpage for an example of setuptools.setup

These attributes of setuptools.setup enable installing these types of packages:

  • Packages that are imported to your project and listed in PyPI using setuptools.findpackages:

    packages=find_packages(exclude=["docs","tests", ".gitignore", "README.rst","DESCRIPTION.rst"])

  • Packages not in PyPI, but can be downloaded from a URL using dependency_links

    dependency_links=["http://peak.telecommunity.com/snapshots/",]

Custom functions

In an ideal world, setuptools.setup would handle everything for you. Unfortunately this isn’t always the case. Sometimes you have to do specific things, like installing dependencies with the subprocess command, to get the system you’re installing on in the right state for your package. Try to avoid this, these functions get confusing and often differ between OS and even distribution.