一、软件开发的目录规范

为了提高程序的可读性与可维护性,我们应该为软件设计良好的目录结构,这与规范的编码风格同等重要,简而言之就是把软件代码分文件目录。假设你要写一个ATM软件,你可以按照下面的目录结构管理你的软件代码:

ATM/
|-- core/
|   |-- src.py  # 业务核心逻辑代码
|
|-- api/
|   |-- api.py  # 接口文件
|
|-- db/
|   |-- db_handle.py  # 操作数据文件
|   |-- db.txt  # 存储数据文件
|
|-- lib/
|   |-- common.py  # 共享功能
|
|-- conf/
|   |-- settings.py  # 配置相关
|
|-- bin/
|   |-- run.py  # 程序的启动文件,一般放在项目的根目录下,因为在运行时会默认将运行文件所在的文件夹作为sys.path的第一个路径,这样就省去了处理环境变量的步骤
|
|-- log/
|   |-- log.log  # 日志文件
|
|-- requirements.txt # 存放软件依赖的外部Python包列表,详见https://pip.readthedocs.io/en/1.1/requirements.html
|-- README  # 项目说明文件
# run.py

import sys
import os

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(BASE_DIR)
from core import src

if __name__ == '__main__':
    src.run()
# settings.py

import os

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

DB_PATH = os.path.join(BASE_DIR, 'db', 'db.txt')
LOG_PATH = os.path.join(BASE_DIR, 'log', 'user.log')

# print(DB_PATH)
# print(LOG_PATH)
# src.py

from conf import settings
from lib import common


def login():
    print('登陆')


def register():
    print('注册')
    name = input('username>>: ')
    pwd = input('password>>: ')
    with open(settings.DB_PATH, mode='a', encoding='utf-8') as f:
        f.write('%s:%sn' % (name, pwd))
        # 记录日志。。。。。。
        common.logger('%s注册成功' % name)
        print('注册成功')


def shopping():
    print('购物')


def pay():
    print('支付')


def transfer():
    print('转账')


func_dic = {
    '1': login,
    '2': register,
    '3': shopping,
    '4': pay,
    '5': transfer,
}


def run():
    while True:
        print("""
        1 登陆
        2 注册
        3 购物
        4 支付
        5 转账
        6 退出
        """)
        choice = input('>>>: ').strip()
        if choice == '6': break
        if choice not in func_dic:
            print('输入错误命令,傻叉')
            continue
        func_dic[choice]()
# common.py

import time
from conf import settings


def logger(msg):
    current_time = time.strftime('%Y-%m-%d %X')
    with open(settings.LOG_PATH, mode='a', encoding='utf-8') as f:
        f.write('%s %s' % (current_time, msg))
内容来源于网络如有侵权请私信删除
你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!

相关课程