您的位置:首页 > 编程语言 > Python开发

简单Python程序库开发教程

2015-01-23 09:52 25 查看

1.程序库简介

合理运用程序库将大大提高开发效率,且使系统架构清晰,易于维护,这里所说的程序库,其实就是Python中的包的概念,下面简单介绍Python程序库的开发方法。

2.文件目录结构

waclib			# 程序库名称
-- __init__.py		# 定义包的属性和方法(必须存在)
-- compile.py		# 程序库编译脚本文件
|-- math
|-- __init__.py
|-- core
|-- __init__.py
|-- models
|-- __init__.py
|-- utils
|-- __init__.py



3.文件源码

/compile.py:

#-*- coding: utf-8 -*-

import os
import compileall

"""
* py_compile *
This module allows you to explicitly compile Python modules
to bytecode. It behaves like Python’s import statement,
but takes a file name, not a module name.
"""
"""
* compileall *
This module contains functions to compile all Python scripts
in a given directory (or along the Python path) to bytecode.
It can also be used as a script (on Unix platforms, it’s
automatically run when Python is installed).
"""

def get_package_list():
cur_dir = os.getcwd()
files = os.listdir(cur_dir)
dirs = []   # packages
for file in files:
if os.path.isdir(file):
dirs.append(file)
return dirs

def exec_compile(package_list):
for package in package_list:
compileall.compile_dir(package, force=1)

# package defines
package_list = get_package_list()

# compile all
print "This may take a while!"
exec_compile(package_list)


/math/__init__.py:

#-*- coding: utf-8 -*-

def add(num1, num2):
""" 加法 """
return (num1 + num2)

def sub(num1, num2):
""" 减法 """
return (num1 - num2)



4. 程序库编译

进入waclib目录下,执行命令python compile.py,即可对程序库完成编译!
目录下的所有脚本文件编译,将/home/wackey目录下的所有.py文件编译成.pyc文件:

python -m py_compile /home/wackey/*.py
程序实现:

import py_compile
py_compile.compile('path') //path是包括.py文件名的路径


5.程序库调用

在waclib的同级目录下,创建test.py文件,内容如下:
from waclib import math

print math.add(1, 2)
print math.sub(5, 9)


6.程序库打包安装

至此,Python程序库教程完毕!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: