问题:从子文件夹导入模块

我想将子文件夹作为模块导入。因此,每个子文件夹都包含一个__init__.py。我的文件夹结构是这样的:

src\
  main.py
  dirFoo\
    __init__.py
    foofactory.py
    dirFoo1\
      __init__.py
      foo1.py
    dirFoo2\
      __init__.py
      foo2.py

在我的主脚本中,导入

from dirFoo.foofactory import FooFactory

在此工厂文件中,我包括以下子模块:

from dirFoo1.foo1 import Foo1
from dirFoo2.foo2 import Foo2

如果我叫我的foofactory我得到了错误,那说明python无法导入子模块foo1和foo2:

Traceback (most recent call last):
  File "/Users/tmp/src/main.py", line 1, in <module>
from dirFoo.foofactory import FooFactory
  File "/Users/tmp/src/dirFoo/foofactory.py", line 1, in    <module>
from dirFoo1.foo1 import Foo1
    ImportError: No module named dirFoo1.foo1

I want to import subfolders as modules. Therefore every subfolder contains a __init__.py. My folder structure is like this:

src\
  main.py
  dirFoo\
    __init__.py
    foofactory.py
    dirFoo1\
      __init__.py
      foo1.py
    dirFoo2\
      __init__.py
      foo2.py

In my main script I import

from dirFoo.foofactory import FooFactory

In this factory file I include the sub modules:

from dirFoo1.foo1 import Foo1
from dirFoo2.foo2 import Foo2

If I call my foofactory I get the error, that python can’t import the submodules foo1 and foo2:

Traceback (most recent call last):
  File "/Users/tmp/src/main.py", line 1, in <module>
from dirFoo.foofactory import FooFactory
  File "/Users/tmp/src/dirFoo/foofactory.py", line 1, in    <module>
from dirFoo1.foo1 import Foo1
    ImportError: No module named dirFoo1.foo1

回答 0

无需与您PYTHONPATHsys.path此处混淆。

为了在包中正确使用绝对导入,还应该包括“ root”包名,例如:

from dirFoo.dirFoo1.foo1 import Foo1
from dirFoo.dirFoo2.foo2 import Foo2

或者您可以使用相对导入

from .dirfoo1.foo1 import Foo1
from .dirfoo2.foo2 import Foo2

There’s no need to mess with your PYTHONPATH or sys.path here.

To properly use absolute imports in a package you should include the “root” packagename as well, e.g.:

from dirFoo.dirFoo1.foo1 import Foo1
from dirFoo.dirFoo2.foo2 import Foo2

Or you can use relative imports:

from .dirfoo1.foo1 import Foo1
from .dirfoo2.foo2 import Foo2

回答 1

只是在这里通知。(来自新蜜蜂keviv22)

永远不要为了自己的利益而用“-”或“ _”之类的符号命名文件夹或文件。如果这样做,您可能会遇到一些问题。就像我的一样,尽管导入命令正确无误,但您将无法成功导入所需的文件,这些文件在此类命名文件夹中可用。

无效的文件夹命名如下:

  • 通用类文件夹
  • Generic_Classes_Folder

上面的有效文件夹命名:

  • GenericClassesFolder或Genericclassesfolder或genericClassesFolder(或类似的词,单词之间没有任何空格或特殊符号)

我犯了什么错误:

考虑文件结构。

Parent
   . __init__.py
   . Setup
     .. __init__.py
     .. Generic-Class-Folder
        ... __init__.py
        ... targetClass.py
   . Check
     .. __init__.py
     .. testFile.py

我想做什么?

  • 从testFile.py,我想在Generic-Class-Folder文件中导入“ targetClass.py”文件,以在“ targetClass.py”文件中使用名为“ functionExecute”的函数

我做了什么命令?

  • 来自“ testFile.py”,写了命令, from Core.Generic-Class-Folder.targetClass import functionExecute
  • 有类似的错误 SyntaxError: invalid syntax

尝试了许多搜索并查看了许多stackoverflow问题,但无法确定出了什么问题。我多次交叉检查文件,使用__init__.py文件,插入环境路径,非常担心出了什么问题……

在很长很长一段时间后,我在和我的一个朋友交谈时想出了这一点。使用这样的命名约定我并不傻。我绝对不要使用空格或特殊符号为任何文件夹或文件定义名称。所以,这就是我想传达的。祝你有美好的一天!

(很抱歉在此发布大量文章……只是让我的挫败感….::)谢谢!)

Just to notify here. (from a newbee, keviv22)

Never and ever for the sake of your own good, name the folders or files with symbols like “-” or “_”. If you did so, you may face few issues. like mine, say, though your command for importing is correct, you wont be able to successfully import the desired files which are available inside such named folders.

Invalid Folder namings as follows:

  • Generic-Classes-Folder
  • Generic_Classes_Folder

valid Folder namings for above:

  • GenericClassesFolder or Genericclassesfolder or genericClassesFolder (or like this without any spaces or special symbols among the words)

What mistake I did:

consider the file structure.

Parent
   . __init__.py
   . Setup
     .. __init__.py
     .. Generic-Class-Folder
        ... __init__.py
        ... targetClass.py
   . Check
     .. __init__.py
     .. testFile.py

What I wanted to do?

  • from testFile.py, I wanted to import the ‘targetClass.py’ file inside the Generic-Class-Folder file to use the function named “functionExecute” in ‘targetClass.py’ file

What command I did?

  • from ‘testFile.py’, wrote command, from Core.Generic-Class-Folder.targetClass import functionExecute
  • Got errors like SyntaxError: invalid syntax

Tried many searches and viewed many stackoverflow questions and unable to decide what went wrong. I cross checked my files multiple times, i used __init__.py file, inserted environment path and hugely worried what went wrong……

And after a long long long time, i figured this out while talking with a friend of mine. I am little stupid to use such naming conventions. I should never use space or special symbols to define a name for any folder or file. So, this is what I wanted to convey. Have a good day!

(sorry for the huge post over this… just letting my frustrations go…. :) Thanks!)


回答 2

设置您的PYTHONPATH环境变量。例如这样的PYTHONPATH =。:..(对于* nix系列)。

您也可以手动将当前目录(在您的情况下为src)添加到pythonpath中:

import os
import sys
sys.path.insert(0, os.getcwd())

Set your PYTHONPATH environment variable. For example like this PYTHONPATH=.:.. (for *nix family).

Also you can manually add your current directory (src in your case) to pythonpath:

import os
import sys
sys.path.insert(0, os.getcwd())

回答 3

假设您的项目采用以下结构:

+---MyPythonProject
|   +---.gitignore
|   +---run.py
|   |   +---subscripts
|   |   |   +---script_one.py
|   |   |   +---script_two.py

run.py,您可以通过以下方式导入脚本一和二:

from subscripts import script_one as One
from subscripts import script_two as Two

现在,仍然在内run.py,您可以使用以下命令调用其方法:

One.method_from_one(param)
Two.method_from_two(other_param)

Say your project is structured this way:

+---MyPythonProject
|   +---.gitignore
|   +---run.py
|   |   +---subscripts
|   |   |   +---script_one.py
|   |   |   +---script_two.py

Inside run.py, you can import scripts one and two by:

from subscripts import script_one as One
from subscripts import script_two as Two

Now, still inside run.py, you’ll be able to call their methods with:

One.method_from_one(param)
Two.method_from_two(other_param)

回答 4

只需创建一个空的____init____.py文件,并将其添加到root以及您拥有其他python模块的python应用程序的所有子目录/文件夹中即可。

Just create an empty __init__.py file and add it in root as well as all the sub directory/folder of your python application where you have other python modules. See https://docs.python.org/3/tutorial/modules.html#packages


回答 5

即使子文件夹中存在init .py且在导入后添加“ as” 时仍存在问题

from folder.file import Class as Class
import folder.file as functions

Had problems even when init.py existed in subfolder and all that was missing was adding ‘as’ after import

from folder.file import Class as Class
import folder.file as functions

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。