详细一看就懂得Python包概念( 二 )


  • 绝对导入:以glance作为起始
  • 相对导入:用.或者..的方式最为起始(只能在一个包中使用 , 不能用于不同目录内)
例如:我们在glance/api/version.py中想要导入glance/cmd/manage.py
在glance/api/version.py#绝对导入from glance.cmd import managemanage.main()#相对导入from ..cmd import managemanage.main()【详细一看就懂得Python包概念】测试结果:注意一定要在于glance同级的文件中测试
from glance.api import versions 特别需要注意的是:可以用import导入内置或者第三方模块(已经在sys.path中) , 但是要绝对避免使用import来导入自定义包的子模块(没有在sys.path中) , 应该使用from... import ...的绝对或者相对导入,且包的相对导入只能用from的形式 。
绝对导入
glance/├── __init__.pyfrom glance import apifrom glance import cmdfrom glance import db├── api│├── __init__.pyfrom glance.api import policyfrom glance.api import versions│├── policy.py│└── versions.py├── cmdfrom glance.cmd import manage│├── __init__.py│└── manage.py└── dbfrom glance.db import models├── __init__.py└── models.py相对导入
glance/├── __init__.pyfrom . import api#.表示当前目录from . import cmdfrom . import db├── api│├── __init__.pyfrom . import policyfrom . import versions│├── policy.py│└── versions.py├── cmdfrom . import manage│├── __init__.py│└── manage.pyfrom ..api import policy#..表示上一级目录 , 想再manage中使用policy中的方法就需要回到上一级glance目录往下找api包 , 从api导入policy└── dbfrom . import models├── __init__.py└── models.py单独导入包
单独导入包名称时不会导入包中所有包含的所有子模块 , 如
#在与glance同级的test.py中import glanceglance.cmd.manage.main()'''执行结果:AttributeError: module 'glance' has no attribute 'cmd''''解决办法
#glance/__init__.pyfrom . import cmd#glance/cmd/__init__.pyfrom . import manage执行
#在于glance同级的test.py中import glanceglance.cmd.manage.main()ps注意:__all__不能解决吗 , __all__是用于控制from...import *
import glance之后直接调用模块中的方法import glance
glance/├── __init__.pyfrom .api import *from .cmd import *from .db import *├── api│├── __init__.py__all__ = ['policy','versions'] │├── policy.py│└── versions.py├── cmd__all__ = ['manage']│├── __init__.py│└── manage.py└── db__all__ = ['models']├── __init__.py└── models.pyimport glancepolicy.get()软件开发规范
详细一看就懂得Python包概念

文章插图
 
示例代码
#=============>bin目录:存放执行脚本#start.pyimport sys,osBASE_DIR=os.path.dirname(os.path.dirname(os.path.abspath(__file__)))sys.path.append(BASE_DIR)from core import corefrom conf import my_log_settingsif __name__ == '__main__':my_log_settings.load_my_logging_cfg()core.run()#=============>conf目录:存放配置文件#config.ini[DEFAULT]user_timeout = 1000[egon]password = 123money = 10000000[alex]password = alex3714money=10000000000[yuanhao]password = ysb123money=10#settings.pyimport osconfig_path=r'%s%s' %(os.path.dirname(os.path.abspath(__file__)),'config.ini')user_timeout=10user_db_path=r'%s%s' %(os.path.dirname(os.path.dirname(os.path.abspath(__file__))),'db')#my_log_settings.py"""logging配置"""import osimport logging.config# 定义三种日志输出格式 开始standard_format = '[%(asctime)s][%(threadName)s:%(thread)d][task_id:%(name)s][%(filename)s:%(lineno)d]''[%(levelname)s][%(message)s]' #其中name为getlogger指定的名字simple_format = '[%(levelname)s][%(asctime)s][%(filename)s:%(lineno)d]%(message)s'id_simple_format = '[%(levelname)s][%(asctime)s] %(message)s'# 定义日志输出格式 结束logfile_dir = r'%slog' %os.path.dirname(os.path.dirname(os.path.abspath(__file__)))# log文件的目录logfile_name = 'all2.log'# log文件名# 如果不存在定义的日志目录就创建一个if not os.path.isdir(logfile_dir):os.mkdir(logfile_dir)# log文件的全路径logfile_path = os.path.join(logfile_dir, logfile_name)# log配置字典LOGGING_DIC = {'version': 1,'disable_existing_loggers': False,'formatters': {'standard': {'format': standard_format},'simple': {'format': simple_format},},'filters': {},'handlers': {#打印到终端的日志'console': {'level': 'DEBUG','class': 'logging.StreamHandler',# 打印到屏幕'formatter': 'simple'},#打印到文件的日志,收集info及以上的日志'default': {'level': 'DEBUG','class': 'logging.handlers.RotatingFileHandler',# 保存到文件'formatter': 'standard','filename': logfile_path,# 日志文件'maxBytes': 1024*1024*5,# 日志大小 5M'backupCount': 5,'encoding': 'utf-8',# 日志文件的编码 , 再也不用担心中文log乱码了},},'loggers': {#logging.getLogger(__name__)拿到的logger配置'': {'handlers': ['default', 'console'],# 这里把上面定义的两个handler都加上 , 即log数据既写入文件又打印到屏幕'level': 'DEBUG','propagate': True,# 向上(更高level的logger)传递},},}def load_my_logging_cfg():logging.config.dictConfig(LOGGING_DIC)# 导入上面定义的logging配置logger = logging.getLogger(__name__)# 生成一个log实例logger.info('It works!')# 记录该文件的运行状态if __name__ == '__main__':load_my_logging_cfg()#=============>core目录:存放核心逻辑#core.pyimport loggingimport timefrom conf import settingsfrom lib import read_iniconfig=read_ini.read(settings.config_path)logger=logging.getLogger(__name__)current_user={'user':None,'login_time':None,'timeout':int(settings.user_timeout)}def auth(func):def wrapper(*args,**kwargs):if current_user['user']:interval=time.time()-current_user['login_time']if interval < current_user['timeout']:return func(*args,**kwargs)name = input('name>>: ')password = input('password>>: ')if config.has_section(name):if password == config.get(name,'password'):logger.info('登录成功')current_user['user']=namecurrent_user['login_time']=time.time()return func(*args,**kwargs)else:logger.error('用户名不存在')return wrapper@authdef buy():print('buy...')@authdef run():print('''购物查看余额转账''')while True:choice = input('>>: ').strip()if not choice:continueif choice == '1':buy()if __name__ == '__main__':run()#=============>db目录:存放数据库文件#run1_json#run2_json#=============>lib目录:存放自定义的模块与包#read_ini.pyimport configparserdef read(config_file):config=configparser.ConfigParser()config.read(config_file)return config#=============>log目录:存放日志#all2.log[2017-07-29 00:31:40,272][MainThread:11692][task_id:conf.my_log_settings][my_log_settings.py:75][INFO][It works!][2017-07-29 00:31:41,789][MainThread:11692][task_id:core.core][core.py:25][ERROR][用户名不存在][2017-07-29 00:31:46,394][MainThread:12348][task_id:conf.my_log_settings][my_log_settings.py:75][INFO][It works!][2017-07-29 00:31:47,629][MainThread:12348][task_id:core.core][core.py:25][ERROR][用户名不存在][2017-07-29 00:31:57,912][MainThread:10528][task_id:conf.my_log_settings][my_log_settings.py:75][INFO][It works!][2017-07-29 00:32:03,340][MainThread:12744][task_id:conf.my_log_settings][my_log_settings.py:75][INFO][It works!][2017-07-29 00:32:05,065][MainThread:12916][task_id:conf.my_log_settings][my_log_settings.py:75][INFO][It works!][2017-07-29 00:32:08,181][MainThread:12916][task_id:core.core][core.py:25][ERROR][用户名不存在][2017-07-29 00:32:13,638][MainThread:7220][task_id:conf.my_log_settings][my_log_settings.py:75][INFO][It works!][2017-07-29 00:32:23,005][MainThread:7220][task_id:core.core][core.py:20][INFO][登录成功][2017-07-29 00:32:40,941][MainThread:7220][task_id:core.core][core.py:20][INFO][登录成功][2017-07-29 00:32:47,222][MainThread:7220][task_id:core.core][core.py:20][INFO][登录成功][2017-07-29 00:32:51,949][MainThread:7220][task_id:core.core][core.py:25][ERROR][用户名不存在][2017-07-29 00:33:00,213][MainThread:7220][task_id:core.core][core.py:20][INFO][登录成功][2017-07-29 00:33:50,118][MainThread:8500][task_id:conf.my_log_settings][my_log_settings.py:75][INFO][It works!][2017-07-29 00:33:55,845][MainThread:8500][task_id:core.core][core.py:20][INFO][登录成功][2017-07-29 00:34:06,837][MainThread:8500][task_id:core.core][core.py:25][ERROR][用户名不存在][2017-07-29 00:34:09,405][MainThread:8500][task_id:core.core][core.py:25][ERROR][用户名不存在][2017-07-29 00:34:10,645][MainThread:8500][task_id:core.core][core.py:25][ERROR][用户名不存在]


推荐阅读