python学习_软件开发的目录规范以及示例代码(解决软件移植的路径问题)

目录结构:

Package
|------bin
    |------start.py
|------conf
    |------settings.py
|------core
    |------src.py
|------db
    |------table.db
|------lib
    |------common.py
|------log
    |------transaction.log
|------README

 1.在src中编写核心代码

from lib import common

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


def pay():
    print()
    common.logger('XXXXXXXXXX')


def transfer():
    print()


def withdraw():
    print('提现')


func_dic={
    '1': shopping,
    '2': pay,
    '3': transfer,
    '4': withdraw
}

#让用户选择启动哪个方法
def run():
    while True:
        print("""
        0 退出
        1 购物
        2 支付
        3 转账
        4 提现
        """)
        choice =input('请输入您的操作:').strip()
        if choice == '0':break
        if choice not in func_dic:
            print("输入的指令不存在,请重新输入")
            continue
        func_dic[choice]()

2.bin/start为程序启动入口

os.path.dirname(os.path.dirname(__file__))================>动态获取软件的根目录,解决移植问题

import sys
import os
from core import src

BASE_DIR = os.path.dirname(os.path.dirname(__file__))
sys.path.append(BASE_DIR)

if __name__ == '__main__':
    src.run()

3.conf/settings.py中设置日志路径(以及数据库路径)

  同样是动态获取软件的根目录,再拼接到软件日志的指定目录,解决移植问题

import os
BASE_DIR=os.path.dirname(os.path.dirname(__file__))
TRANSACTION_LOG_PATH =os.path.join(BASE_DIR, 'log', 'transaction.log')

4.lib/common.py中放通用的方法

from conf import settings
import time
def logger(msg):
    with open(settings.TRANSACTION_LOG_PATH,'at',encoding='utf-8') as f:
        f.write('%s %s\n' %(time.strftime('%Y-%m-%d %H:%M:%S'), msg))

猜你喜欢

转载自www.cnblogs.com/cooky/p/9375207.html