• Python--软件目录结构


    目的不必多说:提高项目可读性、可维护性

    软件目录结构示例:

    Game/
    |-- bin/
    |   |-- game.py
    |
    |-- core/
    |   |-- tests/
    |   |   |-- __init__.py
    |   |   |-- test_main.py
    |   |
    |   |-- __init__.py
    |   |-- main.py
    |
    |-- logs/
    |   |-- err.log
    |   |-- run.log
    |
    |-- conf/
    |   |-- setting.py
    |   |-- abc.rst
    |
    |-- setup.py
    |-- requirements.txt
    |-- README

    那么问题来了,当类似于如上的目录结构时,我怎么在game.py中去调用setting.py或者main.py中的函数呢???

    解(有解给2分):

    首先,需要通过os.path.abspath(__file__)获取到game.py的绝对路径,进而方便找到setting.py文件的位置

    然后,再通过os.path.dirname()方法回到文件的父级目录以及更上级的目录

    最后,将项目的绝对路径通过sys.path.append()添加到系统环境变量中

    此时,就可以调用啦,上栗子(真香!!!)

    setting.py

    1 def Aset():
    2     print("这里是配置")

    main.py

    1 def hello(name):
    2     print("hello,%s,这里是主函数" % name)

    game.py

     1 import  os
     2 import sys
     3 
     4 print(os.path.abspath(__file__))
     5 print(os.path.dirname(os.path.abspath(__file__)))
     6 print(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
     7 BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
     8 sys.path.append(BASE_DIR)
     9 
    10 from conf import setting
    11 from core import main
    12 
    13 setting.Aset()
    14 main.hello("tj")
    15 
    16 >>>
    17 F:Python资料第二次学习studyweek4day06Gameingame.py
    18 F:Python资料第二次学习studyweek4day06Gamein
    19 F:Python资料第二次学习studyweek4day06Game
    20 这里是配置
    21 hello,tj,这里是主函数
  • 相关阅读:
    mysql5.5的安装与配置(亲测版)
    CentOS 6.5升级Python和安装IPython(亲测可用)
    运维mysql基础
    linux命令巧用,随手记
    《大话设计模式》——建造者模式
    《大话设计模式》——外观模式
    《大话设计模式》——模版方法模式
    抽象类和接口的区别
    《大话设计模式》——原型模式
    《大话设计模式》——工厂方法模式
  • 原文地址:https://www.cnblogs.com/sunnytomorrow/p/13090181.html
Copyright © 2020-2023  润新知