企业🤖AI Agent构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
## 问题 You’ve written a useful library, and you want to be able to give it away to others. ## 解决方案 If you’re going to start giving code away, the first thing to do is to give it a unique nameand clean up its directory structure. For example, a typical library package might looksomething like this: projectname/ README.txt Doc/ documentation.txt projectname/ __init__.py foo.py bar.py utils/ __init__.py spam.py grok.py examples/ helloworld.py ... To make the package something that you can distribute, first write a setup.py file thatlooks like this: # setup.py from distutils.core import setup setup(name='projectname', version='1.0', author='Your Name', author_email='you@youraddress.com', url='http://www.you.com/projectname', packages=['projectname', 'projectname.utils'], ) Next, make a file MANIFEST.in that lists various nonsource files that you want to includein your package: # MANIFEST.in include *.txt recursive-include examples * recursive-include Doc * Make sure the setup.py and MANIFEST.in files appear in the top-level directory of yourpackage. Once you have done this, you should be able to make a source distribution bytyping a command such as this: % bash python3 setup.py sdist This will create a file such as projectname-1.0.zip or projectname-1.0.tar.gz, dependingon the platform. If it all works, this file is suitable for giving to others or uploading tothe [Python Package Index](http://pypi.python.org/) [http://pypi.python.org/]. ## 讨论 For pure Python code, writing a plain setup.py file is usually straightforward. One potentialgotcha is that you have to manually list every subdirectory that makes up thepackages source code. A common mistake is to only list the top-level directory of apackage and to forget to include package subcomponents. This is why the specificationfor packages in setup.py includes the list packages=[‘projectname', ‘projectname.utils']. As most Python programmers know, there are many third-party packaging options,including setuptools, distribute, and so forth. Some of these are replacements for thedistutils library found in the standard library. Be aware that if you rely on thesepackages, users may not be able to install your software unless they also install therequired package manager first. Because of this, you can almost never go wrong bykeeping things as simple as possible. At a bare minimum, make sure your code can beinstalled using a standard Python 3 installation. Additional features can be supportedas an option if additional packages are available. Packaging and distribution of code involving C extensions can get considerably morecomplicated. Chapter 15 on C extensions has a few details on this. In particular, seeRecipe 15.2.