简单Python程序库开发教程

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程序库教程完毕!

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值