简体   繁体   English

从python中的子文件夹层次结构导入

[英]Importing from sub-folder hierarchy in python

i am trying to import specified modules from test_file hierarchy 我试图从test_file层次结构导入指定的模块

something like : 就像是 :

test_case1.py
test_subsuite_2
test_sub_2.1.1.py
test_suite2

is it possible to do a run import on this hierarchy 是否可以在此层次结构上执行运行导入

/project/main.py
/project/test_files

test_files folder hierarchy is like this : test_files文件夹层次结构如下:

test_files
    test_suite1
        test_case1.py
        test_subsuite_1
            test_sub1_1.py
            test_sub1_2.py
        test_subsuite_2
            test_subsuite_2_1
                test_sub_2.1.1.py
            test_sub2_1.py
            test_sub3_2.py

    test_suite2
        test_case2.py
        test_subsuite2_1
            test_sub21_1.py
            test_sub21_2.py
        test_subsuite2_2
            test_sub22_1.py
            test_sub23_2.py

Create an empty file called __init__.py in all you folders. 在所有文件夹中创建一个名为__init__.py的空文件。 Then you can import using . 然后你可以使用导入. as a folder separator. 作为文件夹分隔符。 Documentation here. 文档在这里。

The key is to create a blank file __init__.py on all subfolders containing the files you want to import. 关键是在包含要导入的文件的所有子文件夹上创建一个空白文件__init__.py In your case, you will have to create the __init__.py files on all of the following folders- 在您的情况下,您必须在以下所有文件夹上创建__init__.py文件 -

  • test_files test_files
  • test_files\\test_suite1 test_files \\ test_suite1
  • test_files\\test_suite1\\test_subsuite_2 test_files \\ test_suite1 \\ test_subsuite_2
  • test_files\\test_suite1\\test_subsuite_2\\test_subsuite_2_1 test_files \\ test_suite1 \\ test_subsuite_2 \\ test_subsuite_2_1

Also, when you import files be careful about specifying the import path correctly, with the entire path from the topmost level specified, and with different folder levels separated by a . 此外,导入文件时要注意正确指定导入路径,指定最顶层的整个路径,并用不同的文件夹级别分隔.
For example, you must import test_case1 by specifying : 例如,您必须通过指定以下内容导入test_case1:

from test_files.test_suite1 import test_case1

Similarly, test_subsuite_2 can be imported by specifying : 同样,可以通过指定test_subsuite_2导入test_subsuite_2

from test_files.test_suite1 import test_subsuite_2

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

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