標籤:python 函數 模組 發布
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='[email protected]'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.6Hello, World!Hello, World!text print more text on the same line
Python 3
print('Python', python_version())print('Hello, World!')print("some text,", end="") print(' print more text on the same line')#結果Python 3.4.1Hello, World!some text, print more text on the same lineprint 'Hello, World!'#報錯File "<ipython-input-3-139a7c5835bd>", line 1print 'Hello, World!'^SyntaxError: invalid syntax
(3)NameError: name ‘sys‘ is not defined解決:import sys代碼更改為:
</pre><pre name="code" class="python">#coding: utf-8import sysdef 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=fhprint "\t",;print filefile=fhprint(each_item, file)
匯入成功:
著作權聲明:歡迎轉載,轉載請註明出處http://blog.csdn.net/ztf312/
《head first python》— 函數定義、模組與發布、共用代碼