Total Pageviews

2016/03/04

[Python] Module your Python Code

In Java, if some source code will be reused by others. We may create a utility class, if someone need this function, he/she can import this class and reuse this function. Do not need to reinvent the wheel.

Assume I have a simple Python code which named printLoop.py, the code is as bellows:
1
2
3
4
""" print movie list"""
def printMovies(movies):
 for movie in movies :
  print(movie)

Supposed that many people may need this function to print the content of array. Therefore, you need to package this Python program as a module.

Step 1. Create a folder for my module which name printLoop


Step 2. Create a setup.py in printLoop folder
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
from distutils.core import setup
setup(
 name = 'printLoop',
 version = '1.0.0',
 py_modules = ['printLoop'],
 author = 'albert',
 author_email = 'xxx@gmail.com',
 url = 'http://xxx.com',
 description = 'simple example for building module',
)

Step 3. Build distribution file
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
D:\python\printLoop>python setup.py sdist
running sdist
running check
warning: sdist: manifest template 'MANIFEST.in' does not exist (using default file list)

warning: sdist: standard file not found: should have one of README, README.txt

writing manifest file 'MANIFEST'
creating printLoop-1.0.0
making hard links in printLoop-1.0.0...
hard linking printLoop.py -> printLoop-1.0.0
hard linking setup.py -> printLoop-1.0.0
creating 'dist\printLoop-1.0.0.zip' and adding 'printLoop-1.0.0' to it
adding 'printLoop-1.0.0\PKG-INFO'
adding 'printLoop-1.0.0\printLoop.py'
adding 'printLoop-1.0.0\setup.py'
removing 'printLoop-1.0.0' (and everything under it)

Step 4. Install the distribution file
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
D:\python\printLoop>python setup.py install
running install
running build
running build_py
creating build
creating build\lib
copying printLoop.py -> build\lib
running install_lib
copying build\lib\printLoop.py -> C:\Users\albert\AppData\Local\Programs\Python\Python35-32\Lib\site-packages
byte-compiling C:\Users\albert\AppData\Local\Programs\Python\Python35-32\Lib\site-packages\printLoop.py to printLoop.cpython-35.pyc
running install_egg_info
Removing C:\Users\albert\AppData\Local\Programs\Python\Python35-32\Lib\site-packages\printLoop-1.0.0-py3.5.egg-info
Writing C:\Users\albert\AppData\Local\Programs\Python\Python35-32\Lib\site-packages\printLoop-1.0.0-py3.5.egg-info

Test.
1. Import printLoop module
2. Create a movie list
3. utilize printLoop.printMovies to print movie list
1
2
3
4
5
6
7
8
9
Python 3.5.1 (v3.5.1:37a07cee5969, Dec  6 2015, 01:38:48) [MSC v.1900 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> import printLoop
>>> movies = ["Inside Out", "The Intern", "Our Brand is Crisis"]
>>> printLoop.printMovies(movies)
Inside Out
The Intern
Our Brand is Crisis
>>> 



No comments: