
run.py
from flask import Flask app = Flask(__name__) flask的源码:
def _get_package_path(name): try: return os.path.abspath(os.path.dirname(sys.modules[name].__file__)) except (KeyError, AttributeError): return os.getcwd() class Flask: def __init__(self, name): self.name = name self.root_path = _get_package_path(self.name) 这其中 _get_package_path 这么写也能获得run.py的根目录:
def _get_package_path(name): try: return os.path.abspath(os.path.dirname(name)) except (KeyError, AttributeError): return os.getcwd() 为什么要加上sys.modules[name].__file__
1 yuankui 2015 年 6 月 15 日 因为函数命名的节操: do what you say,say what you mean 根据函数命名: 这里是要根据模块名,取得模块文件路径 而不是仅仅实现一个功能 另外 如果出现 . └── hello ├── __init__.py └── kitty ├── __init__.py └── real_module.py $ cat hello/__init__.py import kitty.real_module as real_module 的情况hello中的real_module虽然叫做hello.real_module 但是,他的文件路径却在 |