Python模組製作

來源:互聯網
上載者:User

標籤:pytho   uil   mod   進入   windows   blog   目錄結構   i686   引入   

在Python中,每個Python檔案都可以作為一個模組,模組的名字就是檔案的名字。

定義自己的模組

比如有這樣一個檔案test.py,在test.py中定義了函數add

  def add(a,b):        return a+b
調用自己定義的模組

在其他檔案中就可以先import test,然後通過test.add(a,b)來調用了,當然也可以通過from test import add來引入

#fileName:main.pyimport testresult = test.add(11,22)print(result)
測試模組

在實際開中,當一個開發人員編寫完一個模組後,為了讓模組能夠在項目中達到想要的效果,這個開發人員會自行在py檔案中添加一些測試資訊,例如:

#fileName:test.py def add(a,b):        return a+bif __name__ == '__main__':  # 用來進行測試       ret = add(12,22)    print('int test.py file,,,,12+22=%d'%ret)

如果此時,在其他py檔案中引入了此檔案的話,想想看,測試的那段代碼是否也會執行呢!

#fileName:main.pyimport testresult = test.add(11,22)print(result)
模組發布

上面的都是簡單的例子,學會了模組的製作後下來就是發布了,下面就是例子

mymodule目錄結構體如下

.├── setup.py├── suba│   ├── aa.py│   ├── bb.py│   └── __init__.py└── subb    ├── cc.py    ├── dd.py    └── __init__.py
編輯setup.py檔案

py_modules需指明所需包含的py檔案

from distutils.core import setupsetup(name="ylg", version="1.0", description="ylg's module", author="ylg", py_modules=['suba.aa', 'suba.bb', 'subb.cc', 'subb.dd'])
構建模組

執行(window和linux一樣)

python setup.py build

構建後目錄結構

.├── build│   └── lib.linux-i686-2.7│       ├── suba│       │   ├── aa.py│       │   ├── bb.py│       │   └── __init__.py│       └── subb│           ├── cc.py│           ├── dd.py│           └── __init__.py├── setup.py├── suba│   ├── aa.py│   ├── bb.py│   └── __init__.py└── subb    ├── cc.py    ├── dd.py    └── __init__.py

產生發布壓縮包

打包後,產生最終發布壓縮包ylg-1.0.tar.gz , 目錄結構
Windows也可以用壓縮軟體壓縮

.├── build│   └── lib.linux-i686-2.7│       ├── suba│       │   ├── aa.py│       │   ├── bb.py│       │   └── __init__.py│       └── subb│           ├── cc.py│           ├── dd.py│           └── __init__.py├── dist│   └── ylg-1.0.tar.gz├── MANIFEST├── setup.py├── suba│   ├── aa.py│   ├── bb.py│   └── __init__.py└── subb    ├── cc.py    ├── dd.py    └── __init__.py
模組安裝、使用
  • 找到模組的壓縮包
  • 解壓
  • 進入檔案夾
  • 執行命令python setup.py install

註:如果在install的時候,執行目錄安裝,可以使用python setup.py install --prefix=安裝路徑

使用和其他模組一樣就不說了

Python模組製作

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.