简体   繁体   English

从不同目录进行python导入-“尝试从顶级包进行相对导入”

[英]python import from different directory-'attempted relative import beyond top-level package'

proj1
  |__ py1.py
  |__ py2.py
pkg
  |__ __init__.py
  |__ comm_f1.py
  |__mod1
  |  |__ __init__.py
  |  |__ f1.py
  |  |__ f2.py
  |__mod2
  |  |__ __init__.py
  |  |__ f3.py
  |  |__ f4.py

I knew there are some similar questions, but mine seems a little different. 我知道也有类似的问题,但是我的问题似乎有所不同。 I have the project and package directories as above. 我有上面的项目和包目录。 The 'pkg' directory contains some basic functions and classes I will use for my project 'proj1' or 'proj2', etc., so that I don't want to keep 'pkg' under 'proj1'. “ pkg”目录包含一些我将用于项目“ proj1”或“ proj2”等的基本功能和类,因此,我不想将“ pkg”保留在“ proj1”下。 I debugged 'proj1' with VS2015, told it to refer to 'pkg' directory and it works quite well. 我用VS2015调试了“ proj1”,告诉它引用“ pkg”目录,并且效果很好。 But now I create comm_f1.py which has some common functions/classes I believe could be used by different sub modules such as 'mod1' and 'mod2', etc. for example, in f3.py I want to import my class from comm_f1 by using: 但是现在我创建了comm_f1.py,它具有一些常见的函数/类,我相信它们可以被不同的子模块(例如'mod1'和'mod2'等)使用,例如,在f3.py中,我想从comm_f1导入我的类通过使用:

from ..comm_f1 import myclass

It give me an error message 'attempted relative import beyond top-level package' how can I solve this problem elegantly? 它给我一个错误消息“尝试了超出顶级程序包的相对导入”,如何才能优雅地解决此问题? And I don't want to involve the name of 'pkg' (or absolute directory path name with 'pkg') since I probably will change the name of 'pkg' and I suppose since comm_f1.py is only at f3.py's parent directory, it does not necessary need to touch its grand-parent 'pkg' 而且我不想涉及“ pkg”的名称(或绝对目录路径名带有“ pkg”),因为我可能会更改“ pkg”的名称,而且我想因为comm_f1.py仅位于f3.py的父级目录,则无需触摸其祖父母“ pkg”

You can try to expand your path and then import like this 您可以尝试扩展路径,然后像这样导入

import sys
sys.path.append("../")
from comm_f1 import myclass
proj1
  |__ py1.py
  |__ py2.py
pkg
  |__ __init__.py
  |__common
  |  |__ __init__.py
  |  |__ comm_f1.py
  |__mod1
  |  |__ __init__.py
  |  |__ f1.py
  |  |__ f2.py
  |__mod2
  |  |__ __init__.py
  |  |__ f3.py
  |  |__ f4.py

I didn't find an exact solution, but if I put this comm_f1.py into an directory common , claim from comm_f1 import * in the correspondent __init__.py and then I can use everything by using from common import myclass from anywhere. 我没有找到确切的解决方案,但是如果我将comm_f1.py放到common目录中,请from comm_f1 import * __init__.py from comm_f1 import *中声明,然后可以从任何地方使用from common import myclass来使用所有内容。 So I added an module. 所以我添加了一个模块。 I don't know if it is a good solution or it will have any potential problem, but seems working. 我不知道这是否是一个好的解决方案,否则是否有任何潜在的问题,但似乎可以解决。

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

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