简体   繁体   English

Python从上面的目录导入

[英]Python Imports From The Directory Above

I have a directory structure for my python application where in the main folder I have a folder called handlers and in that file I have a base.py that all handlers should inherit from . 我有一个python应用程序的目录结构,在主文件夹中我有一个名为handlers的文件夹,在该文件中我有一个所有处理程序都应该继承的base.py. I also have a folder called users that contains all the handlers relating to users. 我还有一个名为users的文件夹,其中包含与用户相关的所有处理程序。

\main
      \handlers
      base.py
      __init__.py
      \users
                __init__.py
                authenticated.py
                logout.py   

My issue is I can't import the base in any file in the users folder but can import from the users folder. 我的问题是我无法在users文件夹中的任何文件中导入基础,但可以从users文件夹导入。 I know that I have to do something like bellow 我知道我必须做一些像波纹管这样的事情

from ..handlers import *    

But that does not work for some reason all I am trying to do is import base.py into files in the users directory and other directorys I add at a later date. 但是由于某些原因,我无法工作的是将base.py导入到users目录中的文件以及我以后添加的其他directorys中。

import sys
sys.path.append('/your/dir/goes/here')
from base import foo

Something like that should permit you to import stuff from any directory of your choosing. 这样的东西应该允许你从你选择的任何目录中导入东西。

To enable relative import, add main/__init__.py to make main directory into a Python package. 要启用相对导入,请添加main/__init__.py以使main目录成为Python包。 The main 's parent directory should be in sys.path . main的父目录应该在sys.path

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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