标签归档:distribute

如何在setuptools / distribute中包含软件包数据?

问题:如何在setuptools / distribute中包含软件包数据?

使用setuptools / distribute时,我无法使安装程序提取任何package_data文件。我读过的所有内容都表明,以下是正确的方法。有人可以请教吗?

setup(
   name='myapp',
   packages=find_packages(),
   package_data={
      'myapp': ['data/*.txt'],
   },
   include_package_data=True,
   zip_safe=False,
   install_requires=['distribute'],
)

myapp/data/数据文件的位置在哪里。

When using setuptools, I can not get the installer to pull in any package_data files. Everything I’ve read says that the following is the correct way to do it. Can someone please advise?

setup(
   name='myapp',
   packages=find_packages(),
   package_data={
      'myapp': ['data/*.txt'],
   },
   include_package_data=True,
   zip_safe=False,
   install_requires=['distribute'],
)

where myapp/data/ is the location of the data files.


回答 0

我知道这是一个老问题,但人们发现这里通过谷歌自己的方式: package_data是低了下来,肮脏的谎言。它仅在构建二进制软件包(python setup.py bdist ...)时使用,在构建源软件包(python setup.py sdist ...)时不使用。当然,这是荒谬的-人们希望构建源代码分发将导致文件集合,这些文件可以发送给其他人来构建二进制分发。

在任何情况下,使用MANIFEST.in将工作二进制和源分布。

I realize that this is an old question, but for people finding their way here via Google: package_data is a low-down, dirty lie. It is only used when building binary packages (python setup.py bdist ...) but not when building source packages (python setup.py sdist ...). This is, of course, ridiculous — one would expect that building a source distribution would result in a collection of files that could be sent to someone else to built the binary distribution.

In any case, using MANIFEST.in will work both for binary and for source distributions.


回答 1

我只是有同样的问题。解决的方法是简单地删除include_package_data=True

这里阅读之后,我意识到它include_package_data旨在包含来自版本控制的文件,而不是顾名思义仅包含“ include package data”。从文档:

[include_package_data]的数据文件必须处于CVS或Subversion控制之下

如果要对包含的文件进行更细粒度的控制(例如,如果您的软件包目录中有文档文件,并希望将其从安装中排除),则也可以使用package_data关键字。

把那个参数排除掉可以解决这个问题,这恰好是为什么当您切换到distutils时它也可以工作的原因,因为它不接受那个参数。

I just had this same issue. The solution, was simply to remove include_package_data=True.

After reading here, I realized that include_package_data aims to include files from version control, as opposed to merely “include package data” as the name implies. From the docs:

The data files [of include_package_data] must be under CVS or Subversion control

If you want finer-grained control over what files are included (for example, if you have documentation files in your package directories and want to exclude them from installation), then you can also use the package_data keyword.

Taking that argument out fixed it, which is coincidentally why it also worked when you switched to distutils, since it doesn’t take that argument.


回答 2

遵循@Joe的建议删除该include_package_data=True行也对我有用。

详细说明一下,我没有 MANIFEST.in文件。我使用Git而不是CVS。

存储库采用以下形式:

/myrepo
    - .git/
    - setup.py
    - myproject
        - __init__.py
        - some_mod
            - __init__.py
            - animals.py
            - rocks.py
        - config
            - __init__.py
            - settings.py
            - other_settings.special
            - cool.huh
            - other_settings.xml
        - words
            - __init__.py
            word_set.txt

setup.py

from setuptools import setup, find_packages
import os.path

setup (
    name='myproject',
    version = "4.19",
    packages = find_packages(),  
    # package_dir={'mypkg': 'src/mypkg'},  # didnt use this.
    package_data = {
        # If any package contains *.txt or *.rst files, include them:
        '': ['*.txt', '*.xml', '*.special', '*.huh'],
    },

#
    # Oddly enough, include_package_data=True prevented package_data from working.
    # include_package_data=True, # Commented out.
    data_files=[
#               ('bitmaps', ['bm/b1.gif', 'bm/b2.gif']),
        ('/opt/local/myproject/etc', ['myproject/config/settings.py', 'myproject/config/other_settings.special']),
        ('/opt/local/myproject/etc', [os.path.join('myproject/config', 'cool.huh')]),
#
        ('/opt/local/myproject/etc', [os.path.join('myproject/config', 'other_settings.xml')]),
        ('/opt/local/myproject/data', [os.path.join('myproject/words', 'word_set.txt')]),
    ],

    install_requires=[ 'jsonschema',
        'logging', ],

     entry_points = {
        'console_scripts': [
            # Blah...
        ], },
)

python setup.py sdist为源发行版(没有尝试过二进制)运行。

在新的虚拟环境中,我有一个myproject-4.19.tar.gz文件,并且我使用

(venv) pip install ~/myproject-4.19.tar.gz
...

除了将所有内容都安装到我的虚拟环境中之外site-packages,这些特殊数据文件也都安装到/opt/local/myproject/data和中/opt/local/myproject/etc

Following @Joe ‘s recommendation to remove the include_package_data=True line also worked for me.

To elaborate a bit more, I have no MANIFEST.in file. I use Git and not CVS.

Repository takes this kind of shape:

/myrepo
    - .git/
    - setup.py
    - myproject
        - __init__.py
        - some_mod
            - __init__.py
            - animals.py
            - rocks.py
        - config
            - __init__.py
            - settings.py
            - other_settings.special
            - cool.huh
            - other_settings.xml
        - words
            - __init__.py
            word_set.txt

setup.py:

from setuptools import setup, find_packages
import os.path

setup (
    name='myproject',
    version = "4.19",
    packages = find_packages(),  
    # package_dir={'mypkg': 'src/mypkg'},  # didnt use this.
    package_data = {
        # If any package contains *.txt or *.rst files, include them:
        '': ['*.txt', '*.xml', '*.special', '*.huh'],
    },

#
    # Oddly enough, include_package_data=True prevented package_data from working.
    # include_package_data=True, # Commented out.
    data_files=[
#               ('bitmaps', ['bm/b1.gif', 'bm/b2.gif']),
        ('/opt/local/myproject/etc', ['myproject/config/settings.py', 'myproject/config/other_settings.special']),
        ('/opt/local/myproject/etc', [os.path.join('myproject/config', 'cool.huh')]),
#
        ('/opt/local/myproject/etc', [os.path.join('myproject/config', 'other_settings.xml')]),
        ('/opt/local/myproject/data', [os.path.join('myproject/words', 'word_set.txt')]),
    ],

    install_requires=[ 'jsonschema',
        'logging', ],

     entry_points = {
        'console_scripts': [
            # Blah...
        ], },
)

I run python setup.py sdist for a source distrib (haven’t tried binary).

And when inside of a brand new virtual environment, I have a myproject-4.19.tar.gz, file, and I use

(venv) pip install ~/myproject-4.19.tar.gz
...

And other than everything getting installed to my virtual environment’s site-packages, those special data files get installed to /opt/local/myproject/data and /opt/local/myproject/etc.


回答 3

include_package_data=True 为我工作。

如果你使用git,请记住,包括setuptools-gitinstall_requires。远没有拥有Manifest或包含所有路径package_data(在我的情况下,它是具有各种静态特性的django应用程序)那么无聊

(粘贴了我的评论,就像k3-rnc所说的那样,实际上是有帮助的)

include_package_data=True worked for me.

If you use git, remember to include setuptools-git in install_requires. Far less boring than having a Manifest or including all path in package_data ( in my case it’s a django app with all kind of statics )

( pasted the comment I made, as k3-rnc mentioned it’s actually helpful as is )


回答 4

更新:此答案是旧的,该信息不再有效。所有setup.py配置均应使用import setuptools。我在https://stackoverflow.com/a/49501350/64313中添加了更完整的答案


我通过切换到distutils解决了这个问题。似乎已弃用和/或破坏了分发。

from distutils.core import setup

setup(
   name='myapp',
   packages=['myapp'],
   package_data={
      'myapp': ['data/*.txt'],
   },
)

Update: This answer is old and the information is no longer valid. All setup.py configs should use import setuptools. I’ve added a more complete answer at https://stackoverflow.com/a/49501350/64313


I solved this by switching to distutils. Looks like distribute is deprecated and/or broken.

from distutils.core import setup

setup(
   name='myapp',
   packages=['myapp'],
   package_data={
      'myapp': ['data/*.txt'],
   },
)

回答 5

古老的问题,然而… python的软件包管理确实有很多不足之处。因此,我有在本地使用pip安装到指定目录的用例,很惊讶package_data和data_files路径都无法解决。我不希望再向仓库添加另一个文件,所以最终我利用了data_files和setup.py选项–install-data;。像这样的东西

pip install . --install-option="--install-data=$PWD/package" -t package  

Ancient question and yet… package management of python really leaves a lot to be desired. So I had the use case of installing using pip locally to a specified directory and was surprised both package_data and data_files paths did not work out. I was not keen on adding yet another file to the repo so I ended up leveraging data_files and setup.py option –install-data; something like this

pip install . --install-option="--install-data=$PWD/package" -t package  

回答 6

将包含软件包数据的文件夹移到module文件夹为我解决了这个问题。

看到这个问题:MANIFEST.in在“ python setup.py install”上被忽略-没有安装数据文件?

Moving the folder containing the package data into to module folder solved the problem for me.

See this question: MANIFEST.in ignored on “python setup.py install” – no data files installed?


回答 7

我在几天中遇到了同样的问题,但是即使一切都变得混乱,这个线程也无法为我提供帮助。因此,我进行了研究,发现了以下解决方案:

基本上在这种情况下,您应该执行以下操作:

from setuptools import setup

setup(
   name='myapp',
   packages=['myapp'],
   package_dir={'myapp':'myapp'}, # the one line where all the magic happens
   package_data={
      'myapp': ['data/*.txt'],
   },
)

完整的其他stackoverflow答案在这里

I had the same problem for a couple of days but even this thread wasn’t able to help me as everything was confusing. So I did my research and found the following solution:

Basically in this case, you should do:

from setuptools import setup

setup(
   name='myapp',
   packages=['myapp'],
   package_dir={'myapp':'myapp'}, # the one line where all the magic happens
   package_data={
      'myapp': ['data/*.txt'],
   },
)

The full other stackoverflow answer here


回答 8

只需删除该行:

include_package_data=True,

从您的安装脚本中,它将正常工作。(刚刚通过最新的setuptools测试。)

Just remove the line:

include_package_data=True,

from your setup script, and it will work fine. (Tested just now with latest setuptools.)


回答 9

使用setup.cfg(setuptools≥30.3.0)

从setuptools 30.3.0(2016年12月8日发布)开始,您可以保持setup.py很小的规模并将配置移动到setup.cfg文件中。使用这种方法,您可以将包数据放在以下[options.package_data]部分中:

[options.package_data]
* = *.txt, *.rst
hello = *.msg

在这种情况下,您setup.py可以做到:

from setuptools import setup
setup()

有关更多信息,请参阅使用setup.cfg文件配置安装程序

一些关于setup.cfgPEP 518中pyproject.toml提议的弃用赞成的说法,但从2020年2月21日起这仍然是临时的。

Using setup.cfg (setuptools ≥ 30.3.0)

Starting with setuptools 30.3.0 (released 2016-12-08), you can keep your setup.py very small and move the configuration to a setup.cfg file. With this approach, you could put your package data in an [options.package_data] section:

[options.package_data]
* = *.txt, *.rst
hello = *.msg

In this case, your setup.py can be as short as:

from setuptools import setup
setup()

For more information, see configuring setup using setup.cfg files.

There is some talk of deprecating setup.cfg in favour of pyproject.toml as proposed in PEP 518, but this is still provisional as of 2020-02-21.


“错误:选项-无法识别单一版本-外部版本管理”表示什么?

问题:“错误:选项-无法识别单一版本-外部版本管理”表示什么?

error: option --single-version-externally-managed not recognized在加入pip installvarions软件包(包括PyObjCastropy)时似乎突然开始遇到错误。我以前从未见过此错误,但现在它也出现在travis-ci构建中,但没有任何更改。

此错误是否表示已过期?还是某些错误指定的选项setup.py?还是完全其他?

I seem to have suddenly started encounter the error error: option --single-version-externally-managed not recognized when pip installing varions packages (including PyObjC and astropy). I’ve never seen this error before, but it’s now also showing up on travis-ci builds for which nothing has changed.

Does this error indicate an out of date distribute? Or some incorrectly specified option in setup.py? Or something else entirely?


回答 0

新更新:

安装最新版本的setuptools。如果仍然出现错误,请wheel同时安装。

pip install -U setuptools
pip install -U wheel

原始答案/更多详细信息:

--single-version-externally-managed 是用于Python软件包的选项,指示setuptools模块创建一个Python软件包,如果需要,可以由主机的软件包管理器轻松地管理它,例如Yum或Apt。

如果您看到此消息,则可能是旧版本的setuptools或Python。尝试使用Distribute,它是setuptools的较新版本,并且向后兼容。这些软件包可能希望您已经拥有它。

https://pypi.python.org/pypi/distribute

编辑:至此,分发已经合并到主setuptools项目中。只需安装最新版本的setuptools。正如@wynemo指出的那样,您可能希望使用该--egg选项,因为它更适合那些不希望创建要分发的系统软件包的手动安装人员。

New Update:

Install the latest version of setuptools. If you still get the error, install wheel as well.

pip install -U setuptools
pip install -U wheel

Original Answer / More Details:

--single-version-externally-managed is an option used for Python packages instructing the setuptools module to create a Python package which can be easily managed by the host’s package manager if needed, like Yum or Apt.

If you’re seeing this message, you may have an old version of setuptools or Python. Try using Distribute, which is a newer version of setuptools and is backwards compatible. These packages may expect that you have it already.

https://pypi.python.org/pypi/distribute

Edit: At this point, distribute has been merged into the main setuptools project. Just install the latest version of setuptools. As @wynemo indicated, you may wish to use the --egg option instead, as it’s more appropriate for those doing manual installations where you’re not intending to create a system package for distribution.


回答 1

添加--egg选项

pip install --egg SCons

我使用pip1.4.1版

Add --egg option

pip install --egg SCons

I use pip version 1.4.1


回答 2

安装wheel最近解决了这个问题pip(我使用的是8.1.2):

pip install wheel

Installing wheel resolved this issue with recent pip (I used 8.1.2):

pip install wheel

回答 3

尝试像这样升级setuptools:

pip install --upgrade setuptools

Try upgrading setuptools like this:

pip install --upgrade setuptools


回答 4

我有这个问题。原来,我的pip缓存中的文件权限存在问题。

如果您在pip输出的开头看到一条消息,例如

The directory '/home/ubuntu/.cache/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
The directory '/home/ubuntu/.cache/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.

您可能有同样的问题。您可以通过确保对pip缓存具有适当的文件权限(例如chown -R $(whoami) /home/ubuntu/.cache/pip)来解决它,或者,如果您使用的是UNIX,则可以使用XDG_CACHE_HOMEenv var 将pip缓存位置设置为您拥有的某个文件夹。

I was having this problem. It turned out it was a problem with the file permissions on my pip cache.

If you see a message at the very beginning of your pip output like

The directory '/home/ubuntu/.cache/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
The directory '/home/ubuntu/.cache/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.

you might have the same problem. You can resolve it by either ensuring that you have proper file permissions on your pip cache (something like chown -R $(whoami) /home/ubuntu/.cache/pip) or, if you’re on a UNIX, you can set the pip cache location with the XDG_CACHE_HOME env var to some folder you do own.


回答 5

我尝试了上述解决方案。但是,只有执行以下操作,我才能解决该问题:

sudo pip3 install -U pip (对于python3)

I tried the above solutions. However, I only can resolve the problem until I do:

sudo pip3 install -U pip (for python3)


回答 6

当我尝试升级一个python软件包时,我的macbook上也出现此问题。我在OS X中检查了pip版本,它太旧了:1.1。我使用Follow cmd将pip升级到1.5.6

easy_install -U pip

然后,此错误将得到解决。

I have this problem on my macbook also when I try to upgrade one python package. I check pip version in OS X, it’s too old: 1.1. I use follow cmd to upgrade pip to 1.5.6

easy_install -U pip

Then this error is fixed.


为Python安装pip,virtualenv和分发的正确方法是什么?

问题:为Python安装pip,virtualenv和分发的正确方法是什么?

简短问题

背景

4314376问题的回答中,我建议使用,ez_setup以便随后进行安装pipvirtualenv如下所示:

curl -O http://peak.telecommunity.com/dist/ez_setup.py
sudo python ez_setup.py
sudo easy_install pip
sudo pip install virtualenv

我最初是从Jesse Noller的博客文章中删除这些说明的,所以您想在Mac上使用Python吗?。我喜欢保持干净的全局site-packages目录的想法,因此我安装的唯一其他软件包是 virtualenvwrapperand distribute。(distribute由于此Python公共服务公告,我最近添加到了我的工具箱中。要安装这两个软件包,我使用了:

sudo pip install virtualenvwrapper
curl -O http://python-distribute.org/distribute_setup.py
sudo python distribute_setup.py

没有更多的设置工具和easy_install

要真正遵循该Python公共服务声明,在全新安装的Python上,请执行以下操作:

curl -O http://python-distribute.org/distribute_setup.py
sudo python distribute_setup.py
sudo easy_install pip
sudo pip install virtualenv
sudo pip install virtualenvwrapper

雕文的斥责

在对SO问题4314376的回答的评论中,SO用户Glyph说:

没有。永远不要做sudo python setup.py install任何事情。编写〜/ .pydistutils.cfg,将您的pip安装放入〜/ .local或其他内容。特别是命名为的文件ez_setup.py往往会吸收诸如setuptools和easy_install之类的较新版本,这可能会破坏操作系统上的其他内容。

回到简短的问题

因此,Glyph的回答使我想到了最初的问题:

Short Question

Background

In my answer to SO question 4314376, I recommended using ez_setup so that you could then install pip and virtualenv as follows:

curl -O http://peak.telecommunity.com/dist/ez_setup.py
sudo python ez_setup.py
sudo easy_install pip
sudo pip install virtualenv

I originally pulled these instructions from Jesse Noller’s blog post So you want to use Python on the Mac?. I like the idea of keeping a clean global site-packages directory, so the only other packages I install there are virtualenvwrapper and distribute. (I recently added distribute to my toolbox because of this Python public service announcement. To install these two packages, I used:

sudo pip install virtualenvwrapper
curl -O http://python-distribute.org/distribute_setup.py
sudo python distribute_setup.py

No more setuptools and easy_install

To really follow that Python public service announcement, on a fresh Python install, I would do the following:

curl -O http://python-distribute.org/distribute_setup.py
sudo python distribute_setup.py
sudo easy_install pip
sudo pip install virtualenv
sudo pip install virtualenvwrapper

Glyph’s Rebuke

In a comment to my answer to SO question 4314376, SO user Glyph stated:

NO. NEVER EVER do sudo python setup.py install whatever. Write a ~/.pydistutils.cfg that puts your pip installation into ~/.local or something. Especially files named ez_setup.py tend to suck down newer versions of things like setuptools and easy_install, which can potentially break other things on your operating system.

Back to the short question

So Glyph’s response leads me to my original question:


回答 0

您可以执行此操作而无需在python本身中安装任何东西

您不需要sudo或任何特权。

您无需编辑任何文件。

将virtualenv安装到引导虚拟环境中。使用该虚拟环境创建更多内容。由于virtualenv附带了pip和分发,因此您一次安装即可获得所有内容。

  1. 下载virtualenv:
  2. 解压源压缩包
  3. 使用解压缩的tarball创建干净的虚拟环境。该虚拟环境将用于“引导”其他环境。您的所有虚拟环境将自动包含pip和分发。
  4. 使用pip将virtualenv安装到该引导环境中。
  5. 使用该引导环境创建更多内容!

这是bash中的一个示例:

# Select current version of virtualenv:
VERSION=12.0.7
# Name your first "bootstrap" environment:
INITIAL_ENV=bootstrap
# Set to whatever python interpreter you want for your first environment:
PYTHON=$(which python)
URL_BASE=https://pypi.python.org/packages/source/v/virtualenv

# --- Real work starts here ---
curl -O $URL_BASE/virtualenv-$VERSION.tar.gz
tar xzf virtualenv-$VERSION.tar.gz
# Create the first "bootstrap" environment.
$PYTHON virtualenv-$VERSION/virtualenv.py $INITIAL_ENV
# Don't need this anymore.
rm -rf virtualenv-$VERSION
# Install virtualenv into the environment.
$INITIAL_ENV/bin/pip install virtualenv-$VERSION.tar.gz

现在,您可以使用“引导”环境创建更多内容:

# Create a second environment from the first:
$INITIAL_ENV/bin/virtualenv py-env1
# Create more:
$INITIAL_ENV/bin/virtualenv py-env2

发疯!

注意

假设您没有使用过旧的virtualenv版本。旧版本需要标记--no-site-packges(并取决于Python的版本--distribute)。现在,您可以使用just python virtualenv.py path-to-bootstrap或来创建引导环境python3 virtualenv.py path-to-bootstrap

You can do this without installing anything into python itself.

You don’t need sudo or any privileges.

You don’t need to edit any files.

Install virtualenv into a bootstrap virtual environment. Use the that virtual environment to create more. Since virtualenv ships with pip and distribute, you get everything from one install.

  1. Download virtualenv:
  2. Unpack the source tarball
  3. Use the unpacked tarball to create a clean virtual environment. This virtual environment will be used to “bootstrap” others. All of your virtual environments will automatically contain pip and distribute.
  4. Using pip, install virtualenv into that bootstrap environment.
  5. Use that bootstrap environment to create more!

Here is an example in bash:

# Select current version of virtualenv:
VERSION=12.0.7
# Name your first "bootstrap" environment:
INITIAL_ENV=bootstrap
# Set to whatever python interpreter you want for your first environment:
PYTHON=$(which python)
URL_BASE=https://pypi.python.org/packages/source/v/virtualenv

# --- Real work starts here ---
curl -O $URL_BASE/virtualenv-$VERSION.tar.gz
tar xzf virtualenv-$VERSION.tar.gz
# Create the first "bootstrap" environment.
$PYTHON virtualenv-$VERSION/virtualenv.py $INITIAL_ENV
# Don't need this anymore.
rm -rf virtualenv-$VERSION
# Install virtualenv into the environment.
$INITIAL_ENV/bin/pip install virtualenv-$VERSION.tar.gz

Now you can use your “bootstrap” environment to create more:

# Create a second environment from the first:
$INITIAL_ENV/bin/virtualenv py-env1
# Create more:
$INITIAL_ENV/bin/virtualenv py-env2

Go nuts!

Note

This assumes you are not using a really old version of virtualenv. Old versions required the flags --no-site-packges (and depending on the version of Python, --distribute). Now you can create your bootstrap environment with just python virtualenv.py path-to-bootstrap or python3 virtualenv.py path-to-bootstrap.


回答 1

我认为Glyph的意思是这样的:

  1. 创建目录~/.local(如果尚不存在)。
  2. 在你的~/.bashrc,保证~/.local/binPATH~/.localPYTHONPATH
  3. 创建一个~/.pydistutils.cfg包含以下内容的文件

    [install]
    prefix=~/.local

    这是一个标准的ConfigParser格式文件。

  4. 下载 distribute_setup.py并运行python distribute_setup.py(否sudo)。如果它抱怨site-packages目录不存在,请手动创建它:

    mkdir -p〜/ .local / lib / python2.7 / site-packages /

  5. 运行which easy_install以验证它来自~/.local/bin

  6. pip install virtualenv
  7. pip install virtualenvwrapper
  8. 创建一个包含文件夹的虚拟环境,例如 ~/.virtualenvs
  9. ~/.bashrc添加

    export WORKON_HOME
    source ~/.local/bin/virtualenvwrapper.sh

就是这样,根本不使用sudo任何功能,并且您的Python环境在中~/.local,与操作系统的Python完全分开。免责声明:不确定virtualenvwrapper这种情况下的兼容性-我无法在我的系统上测试它:-)

I think Glyph means do something like this:

  1. Create a directory ~/.local, if it doesn’t already exist.
  2. In your ~/.bashrc, ensure that ~/.local/bin is on PATH and that ~/.local is on PYTHONPATH.
  3. Create a file ~/.pydistutils.cfg which contains

    [install]
    prefix=~/.local
    

    It’s a standard ConfigParser-format file.

  4. Download distribute_setup.py and run python distribute_setup.py (no sudo). If it complains about a non-existing site-packages directory, create it manually:

    mkdir -p ~/.local/lib/python2.7/site-packages/

  5. Run which easy_install to verify that it’s coming from ~/.local/bin

  6. Run pip install virtualenv
  7. Run pip install virtualenvwrapper
  8. Create a virtual env containing folder, say ~/.virtualenvs
  9. In ~/.bashrc add

    export WORKON_HOME
    source ~/.local/bin/virtualenvwrapper.sh
    

That’s it, no use of sudo at all and your Python environment is in ~/.local, completely separate from the OS’s Python. Disclaimer: Not sure how compatible virtualenvwrapper is in this scenario – I couldn’t test it on my system :-)


回答 2

如果您按照我在此答案中链接的若干教程中的建议进行操作,则无需在Walker和Vinay的答案中进行一些复杂的“手动”步骤即可获得所需的效果。如果您使用的是Ubuntu:

sudo apt-get install python-pip python-dev

在OS X中,可以通过使用自制软件安装python来实现等效功能(此处有更多详细信息)。

brew install python

随着pip安装,你可以用它来获得剩余的包(可以省略sudo在OS X,如您使用的Python的安装)。

sudo pip install virtualenvwrapper

(这是您需要全局安装的唯一软件包,我怀疑它是否会与操作系统中的任何系统级冲突。如果您想超级安全,可以保留发行版的版本sudo apt-get install virtualenvwrapper

注意:在Ubuntu 14.04中,pip install会出现一些错误,因此我使用pip3 install virtualenv virtualenvwrapper并添加VIRTUALENVWRAPPER_PYTHON=/usr/bin/python3到我的.bashrc/.zshrc文件中。

然后添加到.bashrc文件中

export WORKON_HOME
source /usr/local/bin/virtualenvwrapper.sh

并获取它

. ~/.bashrc

基本上就是这样。现在唯一的决定是是否要创建一个virtualenv来包含系统级程序包

mkvirtualenv --system-site-packages foo

在不需要重新安装现有系统软件包的情况下,它们会与系统解释器的版本符号链接。注意:您仍然可以安装新软件包并升级现有的包含在系统中的软件包,而无需使用sudo-我对其进行了测试,并且它可以在不中断系统解释器的情况下正常运行。

kermit@hocus-pocus:~$ sudo apt-get install python-pandas
kermit@hocus-pocus:~$ mkvirtualenv --system-site-packages s
(s)kermit@hocus-pocus:~$ pip install --upgrade pandas
(s)kermit@hocus-pocus:~$ python -c "import pandas; print(pandas.__version__)"
0.10.1
(s)kermit@hocus-pocus:~$ deactivate
kermit@hocus-pocus:~$ python -c "import pandas; print(pandas.__version__)"
0.8.0

如果您想要一个完全独立的环境,那么另一种方法是

mkvirtualenv --no-site-packages bar

或假设这是默认选项,只需

mkvirtualenv bar

结果是您拥有了一个新的virtualenv,您可以在其中自由而无须地安装自己喜欢的软件包

pip install flask

If you follow the steps advised in several tutorials I linked in this answer, you can get the desired effect without the somewhat complicated “manual” steps in Walker’s and Vinay’s answers. If you’re on Ubuntu:

sudo apt-get install python-pip python-dev

The equivalent is achieved in OS X by using homebrew to install python (more details here).

brew install python

With pip installed, you can use it to get the remaining packages (you can omit sudo in OS X, as you’re using your local python installation).

sudo pip install virtualenvwrapper

(these are the only packages you need installed globally and I doubt that it will clash with anything system-level from the OS. If you want to be super-safe, you can keep the distro’s versions sudo apt-get install virtualenvwrapper)

Note: in Ubuntu 14.04 I receive some errors with pip install, so I use pip3 install virtualenv virtualenvwrapper and add VIRTUALENVWRAPPER_PYTHON=/usr/bin/python3 to my .bashrc/.zshrc file.

You then append to your .bashrc file

export WORKON_HOME
source /usr/local/bin/virtualenvwrapper.sh

and source it

. ~/.bashrc

This is basically it. Now the only decision is whether you want to create a virtualenv to include system-level packages

mkvirtualenv --system-site-packages foo

where your existing system packages don’t have to be reinstalled, they are symlinked to the system interpreter’s versions. Note: you can still install new packages and upgrade existing included-from-system packages without sudo – I tested it and it works without any disruptions of the system interpreter.

kermit@hocus-pocus:~$ sudo apt-get install python-pandas
kermit@hocus-pocus:~$ mkvirtualenv --system-site-packages s
(s)kermit@hocus-pocus:~$ pip install --upgrade pandas
(s)kermit@hocus-pocus:~$ python -c "import pandas; print(pandas.__version__)"
0.10.1
(s)kermit@hocus-pocus:~$ deactivate
kermit@hocus-pocus:~$ python -c "import pandas; print(pandas.__version__)"
0.8.0

The alternative, if you want a completely separated environment, is

mkvirtualenv --no-site-packages bar

or given that this is the default option, simply

mkvirtualenv bar

The result is that you have a new virtualenv where you can freely and sudolessly install your favourite packages

pip install flask

回答 3

从Python 3.4开始

Python 3.3添加了venv模块,Python 3.4添加了surepip模块。这使自举点变得简单:

python -m确保

可能在venv虚拟环境中呼吁这样做之前。

PEP 453中描述了保证的点子。

Python 3.4 onward

Python 3.3 adds the venv module, and Python 3.4 adds the ensurepip module. This makes bootstrapping pip as easy as:

python -m ensurepip

Perhaps preceded by a call to venv to do so inside a virtual environment.

Guaranteed pip is described in PEP 453.


回答 4

在Ubuntu上:

sudo apt-get install python-virtualenv

该软件包python-pip是一个依赖项,因此也将被安装。

On Ubuntu:

sudo apt-get install python-virtualenv

The package python-pip is a dependency, so it will be installed as well.


回答 5

我做了这个程序供我们在工作中使用。

cd ~
curl -s https://pypi.python.org/packages/source/p/pip/pip-1.3.1.tar.gz | tar xvz
cd pip-1.3.1
python setup.py install --user
cd ~
rm -rf pip-1.3.1

$HOME/.local/bin/pip install --user --upgrade pip distribute virtualenvwrapper

# Might want these three in your .bashrc
export PATH=$PATH:$HOME/.local/bin
export VIRTUALENVWRAPPER_VIRTUALENV_ARGS="--distribute"
source $HOME/.local/bin/virtualenvwrapper.sh

mkvirtualenv mypy
workon mypy
pip install --upgrade distribute
pip install pudb # Or whatever other nice package you might want.

安全意识的要点:

  1. curl会进行ssl验证。wget没有。
  2. 从pip 1.3.1开始,pip还执行ssl验证。
  3. 与github tarball相比,更少的用户可以上传pypi tarball。

I made this procedure for us to use at work.

cd ~
curl -s https://pypi.python.org/packages/source/p/pip/pip-1.3.1.tar.gz | tar xvz
cd pip-1.3.1
python setup.py install --user
cd ~
rm -rf pip-1.3.1

$HOME/.local/bin/pip install --user --upgrade pip distribute virtualenvwrapper

# Might want these three in your .bashrc
export PATH=$PATH:$HOME/.local/bin
export VIRTUALENVWRAPPER_VIRTUALENV_ARGS="--distribute"
source $HOME/.local/bin/virtualenvwrapper.sh

mkvirtualenv mypy
workon mypy
pip install --upgrade distribute
pip install pudb # Or whatever other nice package you might want.

Key points for the security minded:

  1. curl does ssl validation. wget doesn’t.
  2. Starting from pip 1.3.1, pip also does ssl validation.
  3. Fewer users can upload the pypi tarball than a github tarball.

回答 6

更新:自2013年7月起,该项目不再维护。作者建议使用pyenv。(pyenv没有对virtualenv的内置支持,但是可以很好地使用它。)

Pythonbrew是python的版本管理器,并支持virtualenv。

使用venvs安装pythonbrew和python版本后,真的很容易:

# Initializes the virtualenv 
pythonbrew venv init

# Create a virtual/sandboxed environment 
pythonbrew venv create mycoolbundle  

# Use it 
pythonbrew venv use mycoolbundle

Update: As of July 2013 this project is no longer maintained. The author suggests using pyenv. (pyenv does not have built-in support for virtualenv, but plays nice with it.)

Pythonbrew is a version manager for python and comes with support for virtualenv.

After installing pythonbrew and a python-version using venvs is really easy:

# Initializes the virtualenv 
pythonbrew venv init

# Create a virtual/sandboxed environment 
pythonbrew venv create mycoolbundle  

# Use it 
pythonbrew venv use mycoolbundle

回答 7

如果您确定这是您要执行的操作,则执行sudo python setup.py安装没有问题。

不同之处在于它将使用操作系统的site-packages目录作为要复制的.py文件的目标。

因此,如果您希望点子在整个范围内都可访问,那可能就是方法。我并不是说其他​​人的方法是不好的,但这可能很公平。

There is no problem to do sudo python setup.py install, if you’re sure it’s what you want to do.

The difference is that it will use the site-packages directory of your OS as a destination for .py files to be copied.

so, if you want pip to be accessible os wide, that’s probably the way to go. I do not say that others way are bad, but this is probably fair enough.


回答 8

安装ActivePython。它包括pip,virtualenv和Distribute。

Install ActivePython. It includes pip, virtualenv and Distribute.


回答 9

我最近遇到了同样的问题。我越来越偏爱“始终使用virtualenv”的心态,所以我的问题是使用pip安装virtualenv,而没有将distribution安装到我的全局目录或用户site-packages目录中。为此,我手动下载了distribute,pip和virtualenv,然后为每个文件运行“ python setup.py install –prefix〜/ .local / python-private”(临时设置为PYTHONPATH =〜/ .local / python-private),以便安装脚本能够找到分发)。我已经将virtualenv脚本移到了我在PATH上的另一个目录中,并对其进行了编辑,以便可以在sys.path上找到分发和virtualenv模块。Tada:我没有在/ usr,/ usr / local或用户站点软件包目录中安装任何东西,但是我可以在任何地方运行virtualenv,在该virtualenv中我得到了pip。

I came across the same problem recently. I’m becoming more partial to the “always use a virtualenv” mindset, so my problem was to install virtualenv with pip without installing distribute to my global or user site-packages directory. To do this, I manually downloaded distribute, pip and virtualenv, and for each one I ran “python setup.py install –prefix ~/.local/python-private” (with a temporary setting of PYTHONPATH=~/.local/python-private) so that setup scripts were able to find distribute). I’ve moved the virtualenv script to another directory I have on my PATH and edited it so that the distribute and virtualenv modules can be found on sys.path. Tada: I did not install anything to /usr, /usr/local or my user site-packages dir, but I can run virtualenv anywhere, and in that virtualenv I get pip.


回答 10

在较旧的操作系统提供的Python版本之上,即使在virtualenv中也安装了升级的SSL模块时,我遇到了各种各样的问题(请参阅下文),所以我现在使用pyenv

pyenv使安装新的Python版本变得非常容易,并支持virtualenvs。入门是比的食谱在其他的答案中所列的virtualenv容易:

  • 在Mac上,键入brew install pyenv,在Linux上,使用pyenv-installer
  • 这将为您提供内置的virtualenv支持以及Python版本切换(如果需要)
  • 与Python 2或3搭配使用时效果很好,可以一次安装多个版本

这样可以很好地将“新Python”版本和virtualenv与系统Python隔离开。因为您可以轻松地使用更新的Python(第2.7.9版),所以SSL模块已经升级,当然,像任何现代的virtualenv设置一样,您与系统Python模块隔离。

一些不错的教程:

pyenv-virtualenv插件现在内建-类型pyenv commands | grep virtualenv检查。我不会首先使用pyenv-virtualenvwrapper插件-了解如何与pyenv集成程度更高的pyenv-virtualenv进行交流,因为这涵盖了virtualenvwrapper的大部分工作。

pyenv建模rbenv(用于Ruby版本切换的好工具),并且其唯一依赖项是bash。

  • pyenv与非常相似的名称无关pyvenv-它是等效的virtualenv,是最新Python 3版本的一部分,并且不处理Python版本切换

注意事项

关于pyenv的两个警告:

  1. 它只能从bash或类似贝壳的作品-或者更具体地说,pyenv-的virtualenv插件不一样dash,这是/bin/sh在Ubuntu或Debian的。
  2. 它必须从交互式登录外壳程序(例如bash --login使用终端)运行,使用诸如Ansible之类的自动化工具并不总是很容易实现

因此,pyenv最适合交互式使用,而对脚本服务器则不太好。

SSL模块问题

使用的原因之一pyenv是,在使用较早的系统提供的Python版本时,升级Python SSL模块常常会遇到问题:

  • Ubuntu 14.04 包含Python 2.7.6,这需要大量的工作才能将其升级到正确的SSL模块,因此它可以将SNI(服务器名称指示)作为客户端进行处理。(我为此编写了一些Ansible脚本,这很痛苦,在某些情况下仍然会中断。)
  • 升级的SSL模块将变得更加重要,因为Python.org网站仅在2017年和2018年才迁移到TLS 1.2

I’ve had various problems (see below) installing upgraded SSL modules, even inside a virtualenv, on top of older OS-provided Python versions, so I now use pyenv.

pyenv makes it very easy to install new Python versions and supports virtualenvs. Getting started is much easier than the recipes for virtualenv listed in other answers:

  • On Mac, type brew install pyenv and on Linux, use pyenv-installer
  • this gets you built-in virtualenv support as well as Python version switching (if required)
  • works well with Python 2 or 3, can have many versions installed at once

This works very well to insulate the “new Python” version and virtualenv from system Python. Because you can easily use a more recent Python (post 2.7.9), the SSL modules are already upgraded, and of course like any modern virtualenv setup you are insulated from the system Python modules.

A couple of nice tutorials:

The pyenv-virtualenv plugin is now built in – type pyenv commands | grep virtualenv to check. I wouldn’t use the pyenv-virtualenvwrapper plugin to start with – see how you get on with pyenv-virtualenv which is more integrated into pyenv, as this covers most of what virtualenvwrapper does.

pyenv is modelled on rbenv (a good tool for Ruby version switching) and its only dependency is bash.

  • pyenv is unrelated to the very similarly named pyvenv – that is a virtualenv equivalent that’s part of recent Python 3 versions, and doesn’t handle Python version switching

Caveats

Two warnings about pyenv:

  1. It only works from a bash or similar shell – or more specifically, the pyenv-virtualenv plugin doesn’t like dash, which is /bin/sh on Ubuntu or Debian.
  2. It must be run from an interactive login shell (e.g. bash --login using a terminal), which is not always easy to achieve with automation tools such as Ansible.

Hence pyenv is best for interactive use, and less good for scripting servers.

SSL module problems

One reason to use pyenv is that there are often problems with upgrading Python SSL modules when using older system-provided Python versions:


回答 11

  • 您可以执行此操作而无需在python本身中安装任何东西。

  • 您不需要sudo或任何特权。

  • 您无需查找virtualenvtar文件的最新版本

  • 您无需在bash脚本中编辑版本信息即可保持最新状态。

  • 你不需要curl/ wgettar安装,也不pipeasy_install

  • 这适用于2.7和3.X

将以下内容保存到/tmp/initvenv.py

将来导入print_function

import os, sys, shutil, tempfile, subprocess, tarfile, hashlib

try:
    from urllib2 import urlopen
except ImportError:
    from urllib.request import urlopen

tmp_dir = tempfile.mkdtemp(prefix='initvenv_')
try:
    # read the latest version from PyPI
    f = urlopen("https://pypi.python.org/pypi/virtualenv/")
    # retrieve the .tar.gz file
    tar_found = False
    url = None
    sha256 = None
    for line in f.read().splitlines():
        if isinstance(line, bytes):
            line = line.decode('utf-8')
        if tar_found:
            if 'sha256' in line:
                sha256 = line.split('data-clipboard-text')[1].split('"')[1]
                break
            continue
        if not tar_found and 'tar.gz">' not in line:
            continue
        tar_found = True
        for url in line.split('"'):
            if url.startswith('https'):
                break
    else:
        print('tar.gz not found')
        sys.exit(1)
    file_name = url.rsplit('/', 1)[1]
    print(file_name)
    os.chdir(tmp_dir)
    data = urlopen(url).read()
    data_sha256 = hashlib.sha256(data).hexdigest()
    if sha256 != data_sha256:
        print('sha256 not correct')
        print(sha256)
        print(data_sha256)
        sys.exit(1)
    with open(file_name, 'wb') as fp:
        fp.write(data)
    tar = tarfile.open(file_name)
    tar.extractall()
    tar.close()
    os.chdir(file_name.replace('.tar.gz', ''))
    print(subprocess.check_output([sys.executable, 'virtualenv.py'] +
                                  [sys.argv[1]]).decode('utf-8'), end='')
    if len(sys.argv) > 2:
        print(subprocess.check_output([
            os.path.join(sys.argv[1], 'bin', 'pip'), 'install', 'virtualenv'] +

            sys.argv[2:]).decode('utf-8'), end='')
except:
    raise
finally:
    shutil.rmtree(tmp_dir)  # always clean up

并用作

python_binary_to_use_in_venv /tmp/initvenv.py your_venv_name [optional packages]

例如(如果您确实需要的distribute兼容性层setuptools

python /tmp/initvenv.py venv distribute

请注意,使用较旧的python版本,这可能会给您InsecurePlatformWarnings¹。

获得virtualenv(例如名称venv)后,您可以使用virtualenv刚刚安装的虚拟环境来设置另一个virtualenv :

venv/bin/virtualenv venv2

虚拟环境包装器

我建议在一次设置后也查看一下virtualenvwrapper

% /opt/python/2.7.10/bin/python /tmp/initvenv.py venv virtualenvwrapper

和激活(可以通过您的登录脚本完成):

% source venv/bin/virtualenvwrapper.sh

您可以执行以下操作:

% mktmpenv 
New python executable in tmp-17bdc3054a46b2b/bin/python
Installing setuptools, pip, wheel...done.
This is a temporary environment. It will be deleted when you run 'deactivate'.
(tmp-17bdc3054a46b2b)% 

¹ 我还没有找到抑制警告的方法。可以在pip和/或中解决它request,但开发人员相互指出是原因。我得到了通常不切实际的建议,将我使用的python版本升级到最新版本。我确信这会中断我的Linux Mint 17安装。幸运的是pip缓存了软件包,因此每次安装软件包时仅发出一次警告。

  • You can do this without installing anything into python itself.

  • You don’t need sudo or any privileges.

  • You don’t need to find the latest version of a virtualenv tar file

  • You don’t need to edit version info in a bash script to keep things up-to-date.

  • You don’t need curl/wget or tar installed, nor pip or easy_install

  • this works for 2.7 as well as for 3.X

Save the following to /tmp/initvenv.py:

from future import print_function

import os, sys, shutil, tempfile, subprocess, tarfile, hashlib

try:
    from urllib2 import urlopen
except ImportError:
    from urllib.request import urlopen

tmp_dir = tempfile.mkdtemp(prefix='initvenv_')
try:
    # read the latest version from PyPI
    f = urlopen("https://pypi.python.org/pypi/virtualenv/")
    # retrieve the .tar.gz file
    tar_found = False
    url = None
    sha256 = None
    for line in f.read().splitlines():
        if isinstance(line, bytes):
            line = line.decode('utf-8')
        if tar_found:
            if 'sha256' in line:
                sha256 = line.split('data-clipboard-text')[1].split('"')[1]
                break
            continue
        if not tar_found and 'tar.gz">' not in line:
            continue
        tar_found = True
        for url in line.split('"'):
            if url.startswith('https'):
                break
    else:
        print('tar.gz not found')
        sys.exit(1)
    file_name = url.rsplit('/', 1)[1]
    print(file_name)
    os.chdir(tmp_dir)
    data = urlopen(url).read()
    data_sha256 = hashlib.sha256(data).hexdigest()
    if sha256 != data_sha256:
        print('sha256 not correct')
        print(sha256)
        print(data_sha256)
        sys.exit(1)
    with open(file_name, 'wb') as fp:
        fp.write(data)
    tar = tarfile.open(file_name)
    tar.extractall()
    tar.close()
    os.chdir(file_name.replace('.tar.gz', ''))
    print(subprocess.check_output([sys.executable, 'virtualenv.py'] +
                                  [sys.argv[1]]).decode('utf-8'), end='')
    if len(sys.argv) > 2:
        print(subprocess.check_output([
            os.path.join(sys.argv[1], 'bin', 'pip'), 'install', 'virtualenv'] +

            sys.argv[2:]).decode('utf-8'), end='')
except:
    raise
finally:
    shutil.rmtree(tmp_dir)  # always clean up

and use it as

python_binary_to_use_in_venv /tmp/initvenv.py your_venv_name [optional packages]

e.g. (if you really need the distribute compatibility layer for setuptools)

python /tmp/initvenv.py venv distribute

Please note that, with older python versions, this might give you InsecurePlatformWarnings¹.

Once you have your virtualenv (name e.g. venv) you can setup another virtualenv by using the virtualenv just installed:

venv/bin/virtualenv venv2

virtualenvwrapper

I recommend taking a look at virtualenvwrapper as well, after a one time setup:

% /opt/python/2.7.10/bin/python /tmp/initvenv.py venv virtualenvwrapper

and activation (can be done from your login script):

% source venv/bin/virtualenvwrapper.sh

you can do things like:

% mktmpenv 
New python executable in tmp-17bdc3054a46b2b/bin/python
Installing setuptools, pip, wheel...done.
This is a temporary environment. It will be deleted when you run 'deactivate'.
(tmp-17bdc3054a46b2b)% 

¹ I have not found a way to suppress the warning. It could be solved in pip and/or request, but the developers point to each other as the cause. I got the, often non-realistic, recommendation to upgrade the python version I was using to the latest version. I am sure this would break e.g my Linux Mint 17 install. Fortunately pip caches packages, so the Warning is made only once per package install.


回答 12

在Virtualenv官方网站上有很好的说明。https://pypi.python.org/pypi/virtualenv

基本上我做什么,是安装pipsudo easy_install pip,然后用于sudo pip install virtualenv再创建一个环境:virtualenv my_env(命名为你想要的),下面是我所做的:virtualenv --distribute my_env; 其安装distributepip在我的virtualenv。

再次,按照virtualenv页面上的说明进行操作。

有点麻烦,来自Ruby; P

There are good instructions on the Virtualenv official site. https://pypi.python.org/pypi/virtualenv

Basically what I did, is install pip with sudo easy_install pip, then used sudo pip install virtualenv then created an environment with: virtualenv my_env (name it what you want), following that I did: virtualenv --distribute my_env; which installed distribute and pip in my virtualenv.

Again, follow the instruction on the virtualenv page.

Kind of a hassle, coming from Ruby ;P


回答 13

这是安装virtualenvwrapper(this的更新)的一种好方法。

下载virtualenv-1.11.4(可在此处找到最新信息),将其解压缩,打开terminal

# Create a bootstrapenv and activate it:
$ cd ~
$ python <path to unzipped folder>/virtualenv.py bootstrapenv
$ source bootstrapenv/bin/activate

# Install virtualenvwrapper:
$ pip install virtualenvwrapper
$ mkdir -p ~/bootstrapenv/Envs

# append it to file `.bashrc`
$ vi ~/.bashrc
  source ~/bootstrapenv/bin/activate
  export WORKON_HOME=~/bootstrapenv/Envs
  source ~/bootstrapenv/bin/virtualenvwrapper.sh

# run it now.
$ source ~/.bashrc

这就是它,现在你可以使用mkvirtualenv env1lsvirtualenv…等

注意:您可以删除virtualenv-1.11.4,并virtualenv-1.11.4.zip从下载文件夹。

Here is a nice way to install virtualenvwrapper(update of this).

Download virtualenv-1.11.4 (you can find latest at here), Unzip it, open terminal

# Create a bootstrapenv and activate it:
$ cd ~
$ python <path to unzipped folder>/virtualenv.py bootstrapenv
$ source bootstrapenv/bin/activate

# Install virtualenvwrapper:
$ pip install virtualenvwrapper
$ mkdir -p ~/bootstrapenv/Envs

# append it to file `.bashrc`
$ vi ~/.bashrc
  source ~/bootstrapenv/bin/activate
  export WORKON_HOME=~/bootstrapenv/Envs
  source ~/bootstrapenv/bin/virtualenvwrapper.sh

# run it now.
$ source ~/.bashrc

That is it, now you can use mkvirtualenv env1, lsvirtualenv ..etc

Note: you can delete virtualenv-1.11.4 and virtualenv-1.11.4.zip from Downloads folders.


回答 14

好消息是,如果您已安装python3.4,则已经安装了pyvenv。所以就

pyvenv project_dir
source project_dir/bin/activate
python --version   
python 3.4.*

现在,在此虚拟环境中,您可以使用pip为该项目安装模块。

离开这个虚拟环境,

deactivate

The good news is if you have installed python3.4, pyvenv is already been installed. So, Just

pyvenv project_dir
source project_dir/bin/activate
python --version   
python 3.4.*

Now in this virtual env, you can use pip to install modules for this project.

Leave this virtual env , just

deactivate

发行版,distutils,setuptools和distutils2之间的区别?

问题:发行版,distutils,setuptools和distutils2之间的区别?

情况

我正在尝试将开放源代码库移植到Python3。(SymPy,如果有人想知道的话。)

因此,2to3在为Python 3构建时,我需要自动运行。为此,我需要使用distribute。因此,我需要移植当前的系统(根据doctest)是distutils


问题

不幸的是,我不知道什么是这些模块-之间的区别distutilsdistributesetuptools。该文档最好是粗略的,因为它们似乎都是彼此的分支,旨在在大多数情况下兼容(但实际上并非全部)……等等。


问题

有人可以解释差异吗?我应该用什么?什么是最现代的解决方案?(Distribute顺便说一句,我也很感谢有关向移植的一些指南,但这超出了问题的范围……)

The Situation

I’m trying to port an open-source library to Python 3. (SymPy, if anyone is wondering.)

So, I need to run 2to3 automatically when building for Python 3. To do that, I need to use distribute. Therefore, I need to port the current system, which (according to the doctest) is distutils.


The Problem

Unfortunately, I’m not sure what’s the difference between these modules—distutils, distribute, setuptools. The documentation is sketchy as best, as they all seem to be a fork of one another, intended to be compatible in most circumstances (but actually, not all)…and so on, and so forth.


The Question

Could someone explain the differences? What am I supposed to use? What is the most modern solution? (As an aside, I’d also appreciate some guide on porting to Distribute, but that’s a tad beyond the scope of the question…)


回答 0

截至2020年3月,该问题的大多数其他答案已经过时了几年。当您遇到有关Python包装问题的建议时,请记住查看发布日期,并且不要相信过时的信息。

Python包装用户指南》值得一读。每个页面上都显示有“最后更新”日期,因此您可以检查手册的最新性,并且内容非常全面。它托管在Python Software Foundation的python.org的子域中,这本身就增加了可信度。“ 项目摘要”页面在这里尤其重要。

工具摘要:

以下是Python封装环境的摘要:

支持的工具:

弃用/废弃的工具:

  • distribute是的叉子setuptools。它共享相同的命名空间,因此,如果您安装了Distribute,则import setuptools实际上将导入使用Distribute分发的软件包。Distribute被合并回Setuptools 0.7中,因此您不再需要使用Distribute。实际上,Pypi上的版本只是安装Setuptools的兼容层。

  • distutils2就是把最好的尝试distutilssetuptoolsdistribute成为列入Python的标准库中的标准工具。想法是distutils2将其分发给旧的Python版本,distutils2并将其重命名packaging为Python 3.3,并将其包含在其标准库中。这些计划没有按计划进行,但是目前distutils2是一个废弃的项目。最新版本于2012年3月发布,其Pypi主页最终已更新以反映其死亡。

其他:

如果您有兴趣,还有其他工具,请阅读《 Python打包用户指南》中的“ 项目摘要 ”。我就不一一列举,不重复该网页,并随时回答匹配的问题,这是只有约distributedistutilssetuptoolsdistutils2

建议:

如果这一切对您来说都是新手,并且您不知道从哪里开始,那么我建议您将学习setuptools,和pipvirtualenv一起很好地结合使用。

如果你正在寻找到virtualenv,你可能有兴趣在这样一个问题:是什么区别venvpyvenvpyenvvirtualenvvirtualenvwrapper,等?。(是的,我知道,我和你一起吟。)

As of March 2020, most of the other answers to this question are several years out-of-date. When you come across advice on Python packaging issues, remember to look at the date of publication, and don’t trust out-of-date information.

The Python Packaging User Guide is worth a read. Every page has a “last updated” date displayed, so you can check the recency of the manual, and it’s quite comprehensive. The fact that it’s hosted on a subdomain of python.org of the Python Software Foundation just adds credence to it. The Project Summaries page is especially relevant here.

Summary of tools:

Here’s a summary of the Python packaging landscape:

Supported tools:

Deprecated/abandoned tools:

  • distribute was a fork of setuptools. It shared the same namespace, so if you had Distribute installed, import setuptools would actually import the package distributed with Distribute. Distribute was merged back into Setuptools 0.7, so you don’t need to use Distribute any more. In fact, the version on Pypi is just a compatibility layer that installs Setuptools.

  • distutils2 was an attempt to take the best of distutils, setuptools and distribute and become the standard tool included in Python’s standard library. The idea was that distutils2 would be distributed for old Python versions, and that distutils2 would be renamed to packaging for Python 3.3, which would include it in its standard library. These plans did not go as intended, however, and currently, distutils2 is an abandoned project. The latest release was in March 2012, and its Pypi home page has finally been updated to reflect its death.

Others:

There are other tools, if you are interested, read Project Summaries in the Python Packaging User Guide. I won’t list them all, to not repeat that page, and to keep the answer matching the question, which was only about distribute, distutils, setuptools and distutils2.

Recommendation:

If all of this is new to you, and you don’t know where to start, I would recommend learning setuptools, along with pip and virtualenv, which all work very well together.

If you’re looking into virtualenv, you might be interested in this question: What is the difference between venv, pyvenv, pyenv, virtualenv, virtualenvwrapper, etc?. (Yes, I know, I groan with you.)


回答 1

我是distutils维护者和distutils2 / packaging贡献者。我在ConFoo 2011上谈论了Python封装,如今,我正在编写它的扩展版本。它尚未发布,因此以下是一些有助于定义内容的摘录。

  • Distutils是用于包装的标准工具。它可以满足简单的需求,但功能有限,扩展范围也不小。

  • Setuptools是一个旨在填补缺少的distutils功能并探索新方向的项目。在某些子社区中,这是事实上的标准。它使用了Python核心开发人员不喜欢的Monkey补丁和魔术。

  • Distribute是Setuptools的一个分支,由开发人员启动,觉得它的开发速度太慢并且无法对其进行开发。当distutils2由同一组启动时,其开发速度大大减慢。2013年8月更新:分发重新合并到setuptools中并停止使用。

  • Distutils2是一个新的distutils库,它是distutils代码库的一个分支,从安装工具(其中一些已在PEP中进行了详细讨论)中汲取了好主意,并且是受pip启发的基本安装程序。 用来导入Distutils2的实际名称packaging在Python 3.3+标准库中,或者distutils2在2.4+和3.1-3.2中。(将很快提供一个反向端口。) Distutils2并未发布Python 3.3版本,因此被搁置了。

更多信息:

我希望很快完成我的指南,它将包含有关每个图书馆的优缺点的更多信息以及过渡指南。

I’m a distutils maintainer and distutils2/packaging contributor. I did a talk about Python packaging at ConFoo 2011 and these days I’m writing an extended version of it. It’s not published yet, so here are excerpts that should help define things.

  • Distutils is the standard tool used for packaging. It works rather well for simple needs, but is limited and not trivial to extend.

  • Setuptools is a project born from the desire to fill missing distutils functionality and explore new directions. In some subcommunities, it’s a de facto standard. It uses monkey-patching and magic that is frowned upon by Python core developers.

  • Distribute is a fork of Setuptools that was started by developers feeling that its development pace was too slow and that it was not possible to evolve it. Its development was considerably slowed when distutils2 was started by the same group. 2013-August update: distribute is merged back into setuptools and discontinued.

  • Distutils2 is a new distutils library, started as a fork of the distutils codebase, with good ideas taken from setup tools (of which some were thoroughly discussed in PEPs), and a basic installer inspired by pip. The actual name you use to import Distutils2 is packaging in the Python 3.3+ standard library, or distutils2 in 2.4+ and 3.1–3.2. (A backport will be available soon.) Distutils2 did not make the Python 3.3 release, and it was put on hold.

More info:

I hope to finish my guide soon, it will contain more info about each library’s strong and weak points and a transition guide.


回答 2

注意:已弃用答案,现在分发已过时。自Python打包机构成立以来,该答案不再有效,并且已经做了很多工作来清理此问题。


是的,您知道了。:-o我认为目前首选的软件包是Distribute,它是setuptools的一个分支,是distutils(原始打包系统)的扩展。Setuptools并未得到维护,因此已被分叉并重命名,但是在安装时,它使用setuptools的软件包名称!我认为大多数Python开发人员现在都使用Distribute,并且可以肯定地说我确实这样做。

NOTE: Answer deprecated, Distribute now obsolete. This answer is no longer valid since the Python Packaging Authority was formed and has done a lot of work cleaning this up.


Yep, you got it. :-o I think at this time the preferred package is Distribute, which is a fork of setuptools, which are an extension of distutils (the original packaging system). Setuptools was not being maintained so is was forked and renamed, however when installed it uses the package name of setuptools! I think most Python developers now use Distribute, and I can say for sure that I do.


回答 3

我意识到我已经回答了您的第二个问题,但没有解决您原始问题中的毫无疑问的假设:

我正在尝试将开放源代码库(SymPy,如果有人想知道)移植到Python3。为此,在构建Python 3时,我需要自动运行2to3。

可能不是需要。其他策略请参见http://docs.python.org/dev/howto/pyporting

为此,我需要使用分配,

可能 :) distutils以不同的分发方式支持代码(不是docstrings)的构建时2to3转换:http : //docs.python.org/dev/howto/pyporting#during-installation

I realize that I have replied to your secondary question without addressing unquestioned assumptions in your original problem:

I’m trying to port an open-source library (SymPy, if anyone is wondering) to Python 3. To do this, I need to run 2to3 automatically when building for Python 3.

You may, not need. Other strategies are described at http://docs.python.org/dev/howto/pyporting

To do that, I need to use distribute,

You may :) distutils supports build-time 2to3 conversion for code (not docstrings), in a different manner that distribute’s: http://docs.python.org/dev/howto/pyporting#during-installation


回答 4

2014年底更新了这个问题,幸运的是,Continuum的“ conda ”软件包管理器已大大消除了Python的包装混乱。

特别是,conda可以快速创建conda“ 环境 ”。您可以使用不同版本的Python配置您的环境。例如:

conda create -n py34 python=3.4 anaconda

conda create -n py26 python=2.6 anaconda

将使用不同版本的Python创建两个(“ py34”或“ py26”)Python环境。

之后,您可以使用以下特定版本的Python调用环境:

source activate <env name>

在必须处理不同版本的Python的情况下,此功能似乎特别有用。

而且,conda具有以下功能:

  • 不可知的Python
  • 跨平台
  • 无需管理员权限
  • 智能依赖性管理(通过SAT求解器)
  • 很好地处理了您可能必须链接的C,Fortran和系统级库

如果您身处科学计算领域,那么最后一点尤其重要。

Updating this question in late 2014 where fortunately the Python packaging chaos has been greatly cleaned up by Continuum’s “conda” package manager.

In particular, conda quickly enables the creation of conda “environments“. You can configure your environments with different versions of Python. For example:

conda create -n py34 python=3.4 anaconda

conda create -n py26 python=2.6 anaconda

will create two (“py34” or “py26”) Python environments with different versions of Python.

Afterwards you can invoke the environment with the specific version of Python with:

source activate <env name>

This feature seems especially useful in your case where you are having to deal with different version of Python.

Moreover, conda has the following features:

  • Python agnostic
  • Cross platform
  • No admin privileges required
  • Smart dependency management (by way of a SAT solver)
  • Nicely deals with C, Fortran and system level libraries that you may have to link against

That last point is especially important if you are in the scientific computing arena.