Python 调用自定义包

创建包

# mkdir -p /python/utils

# touch /python/utils/__init__.py

# vi /python/utils/Log.py
import time
def log(s):
    timestamp = time.time()
    st = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(timestamp))
    return st +' :'+ s;

在Linux的目录下添加__init__.py文件,该目录即成为python的包,该文件用于定义一些规则,比如该包的哪些模块是对外可见的等.该文件可以为空,为空时所有资源对外可见.

定义环境变量

# vi .bash_profile

export PYTHONPATH=$PYTHONPATH:/python/utils

# . ./.bash_profile

以这种方式添加到 PYTHONPATH 变量后, /python/utils 目录下的资源在该用户的任意目录都可以直接引用.

引用自定义包

# python
Python 2.4.3 (#1, Mar  5 2011, 21:25:56)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-50)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>> from Log import log
>>> ll = log('python');
>>> ll
'2016-01-17 00:37:00 :python'
>>>

posted @ 2016-01-17 00:38  方诚  阅读(2030)  评论(0编辑  收藏  举报