如何在python项目中初始化系统的path变量

2024-09-30 15:35:43 发布

您现在位置:Python中文网/ 问答频道 /正文

在项目中有这么多的目录,我希望每个.py文件在单独的目录中,正确地导入其他文件。你知道吗

我试过了

PREFIX = normpath(dirname(dirname(dirname(abspath(__file__)))))
if PREFIX not in sys.path:
    sys.path = [PREFIX] + sys.path

当我想导入其他目录variables时,我只导入这个文件。但是可能太冗长了。你知道吗

有没有更好的方法以更好的方式解决它(除了将项目路径导出到全局系统路径的方法)?你知道吗


Tags: 文件path项目方法py路径目录prefix
2条回答

您可以使用python模块并像这样导入它们:

import MyModule.MySubModule.myclass

例如:

from pixie.libs.setup import Setup

文件夹包括:

/
|-pixie
   |- __init__.py
   |- libs
     |- __init__.py
     |- setup.py
   |- models

比如:https://github.com/masom/Puck/blob/master/client/pixie/controllers/configuration.py#L2

^{} statement包括对packages文件(模块)的支持,这些文件(模块)排列在带有__init__.py标记的目录中。你知道吗

提供了对相对包层次结构(使用前导点)的支持, 因此,绝对模块参考是没有必要的。你知道吗

When specifying what module to import you do not have to specify the absolute name of the module. When a module or package is contained within another package it is possible to make a relative import within the same top package without having to mention the package name. By using leading dots in the specified module or package after from you can specify how high to traverse up the current package hierarchy without specifying exact names. One leading dot means the current package where the module making the import exists. Two dots means up one package level. Three dots is up two levels, etc. So if you execute from . import mod from a module in the pkg package then you will end up importing pkg.mod. If you execute from ..subpkg2 import mod from within pkg.subpkg1 you will import pkg.subpkg2.mod. The specification for relative imports is contained within PEP 328.

您可以将项目安排为子包,并使用类似于的相对导入 from ..subpkg2 import mod使用subpkg2mod的变量 (来自同一级别的任何其他子包)。你知道吗

相关问题 更多 >