1.定义一个函数
假如一个函数已经发布,则升级时,为新添加的变量设定缺省值的设定可以保证不同版本函数的兼容。
def print_lol(the_list, indent=False, level=0, fh=sys.stdout): """ 格式化输出列表(包含嵌套和非嵌套列表),一次显示一行,嵌套列表可以缩进 indent:是否缩进;level:tab缩进个数;fh为写入文件地址,默认显示到屏幕 """ for each_item in the_list: if isinstance(each_item, list): print_lol(each_item,indent,level+1,fh) else: if indent: for tab_stop in range(level): print("\t", end='', file=fh) print(each_item, file=fh)2.函数转化为模块
将函数保存到一个适当命名的文件中nester.py.
3.模块发布
创建一个文件夹命名为nester,新建setup.py文件,包含发布的元数据。首先从python发布工具导入“setup”函数
from distutils.core import setup setup( name = 'nester', version ='1.0.0', py_modules =['nester'], auther ='a' auther_email ='a@s' description ='' )
4.构建发布
发布工具将构建一个发布所需的所有功能,打开cmd命令行,定位到nester文件夹,输入:C:\Python27\python.exe setup.py sdist
屏幕上会出现一组状态,确认发布已经创建。将发布安装到Python本地副本。输入:sudoC:\Python27\python.exe setup.py install
确认本地副本已经安装,出现build和dist两个文件夹。
发布就绪。可以导入模块并使用:import nester
5.上传到PyPI共享
linux:python2.7 setup.py sdist upload
windows:C:\Python27\python.exe setup.py sdist upload
6.debug过程
import模块报错,主要有以下错因:
(1)汉字注释。解决:开头添加#coding: utf-8
(2)书上用python3,实际用python2.7.在同行输出有问题
Python 2
print 'Python', python_version() print 'Hello, World!' print('Hello, World!') print "text", ; print 'print more text on the same line' Python 2.7.6 Hello, World! Hello, World! text print more text on the same linePython 3
print('Python', python_version()) print('Hello, World!') print("some text,", end="") print(' print more text on the same line') #结果 Python 3.4.1 Hello, World! some text, print more text on the same line print 'Hello, World!' #报错 File "<ipython-input-3-139a7c5835bd>", line 1 print 'Hello, World!' ^ SyntaxError: invalid syntax(3)NameError: name 'sys' is not defined 解决:import sys 代码更改为:
</pre><pre name="code" class="python">#coding: utf-8 import sys def print_lol(the_list, indent=False, level=0, fh=sys.stdout): """ 格式化输出列表(包含嵌套和非嵌套列表),一次显示一行,嵌套列表可以缩进 indent:是否缩进;level:tab缩进个数;fh为写入文件地址,默认显示到屏幕 """ for each_item in the_list: if isinstance(each_item, list): print_lol(each_item,indent,level+1,fh) else: if indent: for tab_stop in range(level): file=fh print "\t",;print file file=fh print(each_item, file)
导入成功: