Python函数模块创建、发布和使用

来源:互联网 发布:ss翻墙软件 编辑:程序博客网 时间:2024/06/02 15:27

【本文参考Head First Python 第二章】

可重用的代码块不错,但可共享的模块更棒。

发布工具允许你向全世界共享你的模块--PyPI社区


模块就是一个包含Python代码的文本文件

发布是指一个文件集合,这些文件联合在一起允许你构建、打包和发布你的模块。

一个.py文件示例:

nester.py

def print_lol(the_list,indent=False,level=0):    for each_item in the_list:        if isinstance(each_item, list):            print_lol(each_item,indent,level+1)        else:            if indent:                for tab_stop in range(level):                    print("\t",end='')            print(each_item)

注:这个函数的主要功能:打印列表,每行一个项,在遇到子列表时递归调用该函数。


1.首先为模块创建一个文件夹

将该文件放入某个文件夹(比如新建个nester目录)通过F5执行无报错

2.在新文件夹中创建setup.py文件

from distutils.core import setupsetup(        name = 'nester',        version = '1.3.0',        py_modules = ['nester'],        author = 'hfpython',        author_email = 'hfpython@headfirstlabs.com',        url = 'http://www.headfirstlabs.com',        description = 'A simple printer of nested lists',    )

3.构建一个发布文件

在命令行cmd(或linux shell,这里以windows cmd为例)中执行:python setup.py sdist

注意执行目录为前面新建的文件夹下。


4.将发布安装到Python本地库中使用

python setup.py install


安装好后这个模块就可以在本地使用了,示例文件如下。

import nestercast =['Palin','Clesse',['Idle','Edward'],'Jones',['Gilliam'],'Chapman']print('-------------no indent------------')nester.print_lol(cast)print('----------default indent----------')nester.print_lol(cast,True)print('--- -----specific indent----------')nester.print_lol(cast,True,1)

输出见附录


5.向PyPI上传代码

发布是指一个文件集合,这些文件联合在一起允许你构建、打包和发布你的模块。

首先执行python setup.py register

按照提示输入自己在PyPI的用户名和密码(最后一步保存登陆以后就不用输入了)


然后执行setup.py sdist upload

server responce为200 说明上传成功。



附录:附第4步输出结果

-------------no indent------------PalinClesseIdleEdwardJonesGilliamChapman----------default indent----------PalinClesseIdleEdwardJonesGilliamChapman--- -----specific indent----------PalinClesseIdleEdwardJonesGilliamChapman






0 0
原创粉丝点击