简体   繁体   中英

how to init system's path variable in python projects

in projects There are so Many Directories ,and i want each .py file in separate directory an import other file correctly.

I tried This

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

when i want to import the other directories' variables ,i just import this file.but it may be too verbose.

is there a better way to solve it in a better way(except the way that export the project's path to the global system's path)?

you could use python modules and import them like:

import MyModule.MySubModule.myclass

ex:

from pixie.libs.setup import Setup

the folders are:

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

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

The import statement includes support for packages - files (modules) arranged in directories with __init__.py markers.

Support for relative package hierarchy (using leading dots) is provided, so that absolute module reference is not necessary.

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 . 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 .

You can arrange the projects as sub-packages, and use relative imports similar to from ..subpkg2 import mod to use variables from mod in subpkg2 (from any other sub-package in the same level).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM