在你的机器上安装一个python包foo(也可以在virtualenv中)会有所帮助,这样你就可以从其他项目以及[I]Python提示中导入包foo。
它的作用与pip、easy_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=['wheel', '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=['wheel', '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=['wheel', 'bar', 'greek'], #external packages as dependencies
scripts=[
'scripts/cool',
'scripts/skype',
]
)
long_description 在pypi.org 中用作软件包的 README 描述。
最后,您现在可以将包上传到PyPi.org,以便其他人可以使用pip install yourpackage 安装您的包。
此时有两种选择。
一旦你的包名在pypi.org注册,任何人都不能认领或使用它。 Python packaging suggests the twine package 用于上传(您的包到 PyPi)。因此,
(1) 第一步是在本地构建使用:
# prereq: wheel (pip install wheel)
$ python setup.py sdist bdist_wheel
(2) 然后使用twine 上传到 test.pypi.org 或 pypi.org:
$ twine upload --repository testpypi dist/*
username: ***
password: ***
包需要几分钟才能出现在 test.pypi.org 上。一旦您对它感到满意,您就可以将您的包裹上传到pypi.org 的真实永久索引,只需:
$ twine upload dist/*
或者,您还可以使用GPG 为您的包中的文件签名:
$ twine upload dist/* --sign
额外阅读: