Python setup.py 示例?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4740473/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
setup.py examples?
提问by jedierikb
After studying this page:
研究此页面后:
http://docs.python.org/distutils/builtdist.html
http://docs.python.org/distutils/builtdist.html
I am hoping to find some setup.py files to study so as to make my own (with the goal of making a fedora rpm file).
我希望找到一些 setup.py 文件进行研究,以便制作我自己的(目的是制作 Fedora rpm 文件)。
Could the s.o. community point me towards some good examples?
so 社区能否为我指出一些好的例子?
采纳答案by Rafe Kettler
Complete walkthrough of writing setup.pyscripts here. (with some examples)
在此处完成编写setup.py脚本的演练。(有一些例子)
If you'd like a real-world example, I could point you towards the setup.pyscripts of a couple major projects. Django's is here, pyglet's is here. You can just browse the source of other projects for a file named setup.py for more examples.
如果你想要一个真实世界的例子,我可以为你指出setup.py几个主要项目的脚本。Django 来了,pyglet 来了。您可以浏览其他项目的源文件,获取名为 setup.py 的文件以获取更多示例。
These aren't simple examples; the tutorial link I gave has those. These are more complex, but also more practical.
这些不是简单的例子;我给的教程链接有那些。这些更复杂,但也更实用。
回答by gotgenes
You may find the HitchHiker's Guide to Packaginghelpful, even though it is incomplete. I'd start with the Quick Start tutorial. Try also just browsing through Python packages on the Python Package Index. Just download the tarball, unpack it, and have a look at the setup.pyfile. Or even better, only bother looking through packages that list a public source code repository such as one hosted on GitHub or BitBucket. You're bound to run into one on the front page.
您可能会发现HitchHiker 的包装指南很有帮助,即使它不完整。我将从快速入门教程开始。也可以尝试在Python Package Index上浏览 Python 包。只需下载 tarball,解压缩,然后查看setup.py文件。或者甚至更好,只需费心查看列出公共源代码存储库(例如托管在 GitHub 或 BitBucket 上的存储库)的包。你一定会在头版遇到一个。
My final suggestion is to just go for it and try making one; don't be afraid to fail. I really didn't understand it until I started making them myself. It's trivial to create a new package on PyPI and just as easy to remove it. So, create a dummy package and play around.
我最后的建议是去尝试做一个;不要害怕失败。我真的不明白,直到我开始自己制作它们。在 PyPI 上创建一个新包很简单,删除它也很容易。因此,创建一个虚拟包并进行播放。
回答by Yauhen Yakimovich
READ THIS FIRSThttps://packaging.python.org/en/latest/current.html
首先阅读https://packaging.python.org/en/latest/current.html
Installation Tool Recommendations
- Use pip to install Python packages from PyPI.
- Use virtualenv, or pyvenv to isolate application specific dependencies from a shared Python installation.
- Use pip wheel to create a cache of wheel distributions, for the purpose of > speeding up subsequent installations.
- If you're looking for management of fully integrated cross-platform software stacks, consider buildout (primarily focused on the web development community) or Hashdist, or conda (both primarily focused on the scientific community).
Packaging Tool Recommendations
- Use setuptools to define projects and create Source Distributions.
- Use the bdist_wheel setuptools extension available from the wheel project to create wheels. This is especially beneficial, if your project contains binary extensions.
- Use twine for uploading distributions to PyPI.
安装工具推荐
- 使用 pip 从 PyPI 安装 Python 包。
- 使用 virtualenv 或 pyvenv 将特定于应用程序的依赖项与共享的 Python 安装隔离。
- 使用 pip wheel 创建轮分布缓存,目的是 > 加速后续安装。
- 如果您正在寻找对完全集成的跨平台软件堆栈的管理,请考虑 buildout(主要针对 Web 开发社区)或 Hashdist 或 conda(均主要针对科学社区)。
打包工具推荐
- 使用 setuptools 定义项目并创建源代码分发。
- 使用wheel 项目提供的bdist_wheel setuptools 扩展来创建轮子。如果您的项目包含二进制扩展,这尤其有益。
- 使用 twine 将分布上传到 PyPI。
This anwser has aged, and indeed there is a rescue plan for python packaging world called
这个anwser已经老化了,确实有python打包世界的救援计划叫
wheels way
轮子方式
I qoute pythonwheels.comhere:
我在这里引用pythonwheels.com:
What are wheels?
Wheels are the new standard of python distribution and are intended to replace eggs. Support is offered in pip >= 1.4 and setuptools >= 0.8.
什么是轮子?
Wheels 是 Python 发行版的新标准,旨在取代鸡蛋。支持在 pip >= 1.4 和 setuptools >= 0.8 中提供。
Advantages of wheels
轮子的优点
- Faster installation for pure python and native C extension packages.
- Avoids arbitrary code execution for installation. (Avoids setup.py)
- Installation of a C extension does not require a compiler on Windows or OS X.
- Allows better caching for testing and continuous integration.
- Creates .pyc files as part of installation to ensure they match the python interpreter used.
- More consistent installs across platforms and machines.
- 更快地安装纯 python 和本机 C 扩展包。
- 避免为安装执行任意代码。(避免 setup.py)
- 在 Windows 或 OS X 上安装 C 扩展不需要编译器。
- 为测试和持续集成提供更好的缓存。
- 创建 .pyc 文件作为安装的一部分,以确保它们与使用的 python 解释器匹配。
- 跨平台和机器的更一致的安装。
The full story of correct python packaging (and about wheels) is covered at packaging.python.org
正确的 Python 包装(以及关于轮子)的完整故事在Packaging.python.org 中有介绍
conda way
康达方式
For scientific computing (this is also recommended on packaging.python.org, see above) I would consider using CONDA packagingwhich can be seen as a 3rd party service build on top of PyPI and pip tools. It also works great on setting up your own version of binstarso I would imagine it can do the trick for sophisticated custom enterprise package management.
对于科学计算(这也推荐在 Packaging.python.org 上,见上文)我会考虑使用CONDA 打包,它可以被视为构建在 PyPI 和 pip 工具之上的 3rd 方服务。它也适用于设置您自己的binstar版本,因此我想它可以为复杂的自定义企业包管理提供技巧。
Conda can be installed into a user folder (no super user permisssions) and works like magic with
Conda 可以安装到用户文件夹中(没有超级用户权限)并且像魔术一样工作
conda install
康达安装
and powerful virtual env expansion.
和强大的虚拟环境扩展。
eggs way
鸡蛋方式
This option was related to python-distribute.org and is largerly outdated (as well as the site) so let me point you to one of the ready to use yet compact setup.py examples I like:
这个选项与 python-distribute.org 相关并且已经过时了(以及站点),所以让我向您指出一个我喜欢的即用型但紧凑的 setup.py 示例:
- A very practical example/implementation of mixing scripts and single python files into setup.py is giving here
- Even better one from hyperopt
- 将脚本和单个 python 文件混合到 setup.py 中的一个非常实用的示例/实现在这里给出
- 来自hyperopt 的更好的一个
This quote was taken from the guide on the state of setup.pyand still applies:
这句话取自有关 setup.py 状态的指南,仍然适用:
- setup.py gone!
- distutils gone!
- distribute gone!
- pip and virtualenv here to stay!
- eggs ... gone!
- setup.py 不见了!
- distutils 不见了!
- 分发不见了!
- pip 和 virtualenv 留在这里!
- 鸡蛋……不见了!
I add one more point (from me)
我再加一点(来自我)
- wheels!
- 轮子!
I would recommend to get some understanding of packaging-ecosystem(from the guide pointed by gotgenes) before attempting mindless copy-pasting.
我建议在尝试无意识的复制粘贴之前,先了解一下包装生态系统(来自 gotgenes 指出的指南)。
Most of examples out there in the Internet start with
from distutils.core import setup
but this for example does not support building an egg python setup.py bdist_egg(as well as some other oldfeatures), which were available in
from setuptools import setup
And the reason is that they are deprecated.
Now according to the guide
Warning
Please use the Distribute package rather than the Setuptools package because there are problems in this package that can and will not be fixed.
deprecated setuptools are to be replaced by distutils2, which "will be part of the standard library in Python 3.3". I must say I liked setuptools and eggs and have not yet been completely convinced by convenience of distutils2. It requires
pip install Distutils2
and to install
python -m distutils2.run install
互联网上的大多数示例都以
from distutils.core import setup
但这例如不支持构建egg python setup.py bdist_egg(以及其他一些旧功能),这些功能可在
from setuptools import setup
原因是它们已被弃用。
现在根据指南
警告
请使用 Distribute 包而不是 Setuptools 包,因为此包中存在可以也不会修复的问题。
不推荐使用的 setuptools 将被distutils2替换,它“将成为 Python 3.3 标准库的一部分”。我必须说我喜欢 setuptools 和 egg 并且还没有完全被 distutils2 的便利所说服。这个需要
pip install Distutils2
并安装
python -m distutils2.run install
PS
聚苯乙烯
Packaging never was trivial (one learns this by trying to develop a new one), so I assume a lot of things have gone for reason. I just hope this time it will beis done correctly.
包装从来都不是微不足道的(人们通过尝试开发一个新的来学习这一点),所以我认为很多事情都是有道理的。我只希望这次能正确完成。
回答by Akshar Raaj
Here you will find the simplest possible example of using distutils and setup.py:
在这里你会找到使用 distutils 和 setup.py 的最简单的例子:
https://docs.python.org/2/distutils/introduction.html#distutils-simple-example
https://docs.python.org/2/distutils/introduction.html#distutils-simple-example
This assumes that all your code is in a single file and tells how to package a project containing a single module.
这假设您的所有代码都在一个文件中,并说明如何打包包含单个模块的项目。
回答by Razzi Abuissa
I recommend the setup.pyof the Python Packaging User Guide's example project.
我建议setup.py中的Python的包装用户手册的示例项目。
The Python Packaging User Guide "aims to be the authoritative resource on how to package, publish and install Python distributions using current tools".
Python 打包用户指南“旨在成为有关如何使用当前工具打包、发布和安装 Python 发行版的权威资源”。
回答by marcindulak
Look at this complete example https://github.com/marcindulak/python-mycliof a small python package. It is based on packaging recommendations from https://packaging.python.org/en/latest/distributing.html, uses setup.py with distutils and in addition shows how to create RPM and deb packages.
看看这个完整的例子https://github.com/marcindulak/python-mycli一个小的 python 包。它基于来自https://packaging.python.org/en/latest/distributing.html 的打包建议,将 setup.py 与 distutils 结合使用,此外还展示了如何创建 RPM 和 deb 包。
The project's setup.py is included below (see the repo for the full source):
项目的 setup.py 包含在下面(请参阅 repo 以获取完整源代码):
#!/usr/bin/env python
import os
import sys
from distutils.core import setup
name = "mycli"
rootdir = os.path.abspath(os.path.dirname(__file__))
# Restructured text project description read from file
long_description = open(os.path.join(rootdir, 'README.md')).read()
# Python 2.4 or later needed
if sys.version_info < (2, 4, 0, 'final', 0):
raise SystemExit, 'Python 2.4 or later is required!'
# Build a list of all project modules
packages = []
for dirname, dirnames, filenames in os.walk(name):
if '__init__.py' in filenames:
packages.append(dirname.replace('/', '.'))
package_dir = {name: name}
# Data files used e.g. in tests
package_data = {name: [os.path.join(name, 'tests', 'prt.txt')]}
# The current version number - MSI accepts only version X.X.X
exec(open(os.path.join(name, 'version.py')).read())
# Scripts
scripts = []
for dirname, dirnames, filenames in os.walk('scripts'):
for filename in filenames:
if not filename.endswith('.bat'):
scripts.append(os.path.join(dirname, filename))
# Provide bat executables in the tarball (always for Win)
if 'sdist' in sys.argv or os.name in ['ce', 'nt']:
for s in scripts[:]:
scripts.append(s + '.bat')
# Data_files (e.g. doc) needs (directory, files-in-this-directory) tuples
data_files = []
for dirname, dirnames, filenames in os.walk('doc'):
fileslist = []
for filename in filenames:
fullname = os.path.join(dirname, filename)
fileslist.append(fullname)
data_files.append(('share/' + name + '/' + dirname, fileslist))
setup(name='python-' + name,
version=version, # PEP440
description='mycli - shows some argparse features',
long_description=long_description,
url='https://github.com/marcindulak/python-mycli',
author='Marcin Dulak',
author_email='[email protected]',
license='ASL',
# https://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=[
'Development Status :: 1 - Planning',
'Environment :: Console',
'License :: OSI Approved :: Apache Software License',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.4',
'Programming Language :: Python :: 2.5',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
],
keywords='argparse distutils cli unittest RPM spec deb',
packages=packages,
package_dir=package_dir,
package_data=package_data,
scripts=scripts,
data_files=data_files,
)
and and RPM spec file which more or less follows Fedora/EPEL packaging guidelines may look like:
和和 RPM 规范文件或多或少遵循 Fedora/EPEL 打包指南可能如下所示:
# Failsafe backport of Python2-macros for RHEL <= 6
%{!?python_sitelib: %global python_sitelib %(%{__python} -c "from distutils.sysconfig import get_python_lib; print(get_python_lib())")}
%{!?python_sitearch: %global python_sitearch %(%{__python} -c "from distutils.sysconfig import get_python_lib; print(get_python_lib(1))")}
%{!?python_version: %global python_version %(%{__python} -c "import sys; sys.stdout.write(sys.version[:3])")}
%{!?__python2: %global __python2 %{__python}}
%{!?python2_sitelib: %global python2_sitelib %{python_sitelib}}
%{!?python2_sitearch: %global python2_sitearch %{python_sitearch}}
%{!?python2_version: %global python2_version %{python_version}}
%{!?python2_minor_version: %define python2_minor_version %(%{__python} -c "import sys ; print sys.version[2:3]")}
%global upstream_name mycli
Name: python-%{upstream_name}
Version: 0.0.1
Release: 1%{?dist}
Summary: A Python program that demonstrates usage of argparse
%{?el5:Group: Applications/Scientific}
License: ASL 2.0
URL: https://github.com/marcindulak/%{name}
Source0: https://github.com/marcindulak/%{name}/%{name}-%{version}.tar.gz
%{?el5:BuildRoot: %(mktemp -ud %{_tmppath}/%{name}-%{version}-%{release}-XXXXXX)}
BuildArch: noarch
%if 0%{?suse_version}
BuildRequires: python-devel
%else
BuildRequires: python2-devel
%endif
%description
A Python program that demonstrates usage of argparse.
%prep
%setup -qn %{name}-%{version}
%build
%{__python2} setup.py build
%install
%{?el5:rm -rf $RPM_BUILD_ROOT}
%{__python2} setup.py install --skip-build --prefix=%{_prefix} \
--optimize=1 --root $RPM_BUILD_ROOT
%check
export PYTHONPATH=`pwd`/build/lib
export PATH=`pwd`/build/scripts-%{python2_version}:${PATH}
%if 0%{python2_minor_version} >= 7
%{__python2} -m unittest discover -s %{upstream_name}/tests -p '*.py'
%endif
%clean
%{?el5:rm -rf $RPM_BUILD_ROOT}
%files
%doc LICENSE README.md
%{_bindir}/*
%{python2_sitelib}/%{upstream_name}
%{?!el5:%{python2_sitelib}/*.egg-info}
%changelog
* Wed Jan 14 2015 Marcin Dulak <[email protected]> - 0.0.1-1
- initial version
回答by jozo
回答by voilalex
Here is the utility I wrote to generate a simple setup.pyfile (template) with useful comments and links. I hope, it will be useful.
这是我编写的实用程序,用于生成带有有用注释和链接的简单setup.py文件(模板)。我希望,它会很有用。
Installation
安装
sudo pip install setup-py-cli
Usage
用法
To generate setup.pyfile just type in the terminal.
要生成setup.py文件,只需在终端中输入即可。
setup-py
Now setup.pyfile should occur in the current directory.
现在setup.py文件应该出现在当前目录中。
Generated setup.py
生成的 setup.py
from distutils.core import setup
from setuptools import find_packages
import os
# User-friendly description from README.md
current_directory = os.path.dirname(os.path.abspath(__file__))
try:
with open(os.path.join(current_directory, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
except Exception:
long_description = ''
setup(
# Name of the package
name=<name of current directory>,
# Packages to include into the distribution
packages=find_packages('.'),
# Start with a small number and increase it with every change you make
# https://semver.org
version='1.0.0',
# Chose a license from here: https://help.github.com/articles/licensing-a-repository
# For example: MIT
license='',
# Short description of your library
description='',
# Long description of your library
long_description = long_description,
long_description_context_type = 'text/markdown',
# Your name
author='',
# Your email
author_email='',
# Either the link to your github or to your website
url='',
# Link from which the project can be downloaded
download_url='',
# List of keyword arguments
keywords=[],
# List of packages to install with this one
install_requires=[],
# https://pypi.org/classifiers/
classifiers=[]
)
Content of the generated setup.py:
生成的setup.py 的内容:
- automatically fulfilled package name based on the name of the current directory.
- some basic fields to fulfill.
- clarifying comments and links to useful resources.
- automatically inserted description from README.mdor an empty string if there is no README.md.
- 根据当前目录的名称自动完成的包名称。
- 要完成的一些基本领域。
- 澄清评论和有用资源的链接。
- 如果没有README.md ,则自动插入README.md 中的描述或空字符串。
Here is the linkto the repository. Fill free to enhance the solution.
这是存储库的链接。免费填充以增强解决方案。

