python 打包及发布

1.新建setup.py文件

首先需要在项目中新建setup.py文件,然后编写setup.py。


一个典型的setup.py的写法如下(参考自官方文档):


from distutils.core import setup


#This is a list of files to install, and where
#(relative to the 'root' dir, where setup.py is)
#You could be more specific.
files = ["things/*"]


setup(name = "appname",
version = "100",
description = "yadda yadda",
author = "myself and I",
author_email = "email@someplace.com",
url = "whatever",
#Name the folder where your packages live:
#(If you have other packages (dirs) or modules (py files) then
#put them into the package directory - they will be found 
#recursively.)
packages = ['package'],
#'package' package must contain files (see list above)
#I called the package 'package' thus cleverly confusing the whole issue...
#This dict maps the package name =to=> directories
#It says, package *needs* these files.
package_data = {'package' : files },
#'runner' is in the root.
scripts = ["runner"],
long_description = """Really long text here.""" 
#
#This next part it for the Cheese Shop, look a little down the page.
#classifiers = [] 
)

在setup.py文件中编写 setup()函数,这个函数里面有相当多的属性,比如version表示版本号,description 是描述文档,author是作者等,其中比较重要的几个选项是,name,表示模块的名称。packages,表示包所在的目录,如果我们要打包的所有python文件都在根目录,即和setup.py是一个目录,那么直接写 packages=[""]就可以了。如果python文件在一个单独的文件夹,和setup.py不在同一个目录,则需要写 package_dir=["":"python 文件所在的目录名字"],比如如果有foo1.py 和 foo2.py这两个文件,在src这个文件夹,那么需要写package_dir=["":"src"],同时写packages=[""],打包就可以导入foo1和foo2两个模块了。如果想在同一个包中包含多个模块,比如在foo包中包含foo1和foo2两个模块,则可以直接把foo1.py和foo2.py所在的文件夹直接命名为foo,然后写 packages["foo"] (注意foo文件夹需要有__init__.py这个文件,可以为空,这样才能引用到foo1和foo2)。有的时候我们写的代码需要引入一些额外的信息文件,比如文本文件,或者图片,说明文件等等,这些东西是需要一块打包的,那么这个时候该如何指定呢?此时需要用到 data_files 这个选项了。data_files的写法是:data_files= [('文件要放入的文件夹1',['file1',file2']),('文件要放入的文件夹2',['file3',file4'])],file1,file2等是文件的名称,注意data_files的元素都是元组,元组的第一个元素是文件要放入的文件夹名称,第二个元素是文件列表。这里需要注意的是,如果不想把文件放入文件夹,可以将元组的第一个元素指定为空字符串,此时要打包的文件要被放入根目录,这里根目录是指python解释器所在的目录。比如我需要将文件资源放入python解释器所在目录下的/Lib/site-packages/myfolder路径,myfolder是自定义的文件夹,元组的第一个元素就可以写‘Lib/site-packages/myfolder’,打包时会自动在指定位置新建一个名为myfolder的目录,将文件资源放入其中。

2. 执行打包命令

执行打包命令:python setup.py sdist 为模块创建一个源码包,在当前目录下,会创建dist目录,里面有个文件名为appname.1.0.0.zip,这个就是可以分发的包。使用者拿到这个包后,解压,到 test.1.0.0目录下执行:python setup.py install,那么,包中的.py 文件就会被拷贝到python类路径下,可以被导入使用。

对于Windows,可以执行python setup.py bdist_wininst生成一个exe文件;若要生成RPM包,执行python setup.py bdist_rpm,但系统必须有rpm命令的支持。

发布了99 篇原创文章 · 获赞 60 · 访问量 30万+

猜你喜欢

转载自blog.csdn.net/lengyuewusheng99/article/details/78144322