开发者

Import a module, from inside another module

Basically I have written two modules for my Python Program. I need one mo开发者_Go百科dule to import the other module.

Here is a sample of my file structure.

test_app 
    main.py
    module_1
        __init__.py
        main.py

    module_2
        __init__.py
        main.py

Main.py is able to import either of the two modules, but I need module_1 to import module_2, is that possible?


If you started your program from test_app/main.py, you can just use from module_1 import main in test_app/module_2/main.py file.


If you add an (empty) __init__.py to test_app, test_app will be a package. This means that python will search for modules/packages a bit smarter.

Having done that, in module1, you can now write import test_app.module2 (or import .. module2) and it works.

(This answer was combined from other comments and answers here, hence CW)


Yes. If your PYTHONPATH environment variable is set to test_app, you should be able to import module1 from module2 and vice versa.

I assume that you run your program like this:

python test_app/main.py

and that the program imports module1.main, which in turn imports module2.main. In that case there is no need to alter the value of PYTHONPATH, since Python has already added the test_app directory to it. See the Module Search Path section in the Python docs.


This question ask been answered by the official python documents, in the section called Intra-package References. python modules

The submodules often need to refer to each other. You don't need to care about the PYTHONPATH, declaration of the relative path will do. For your case,

just type "import .. module2" in the module_1/main.py


sure does.

In your module_1 module. In any file:

from module_2 import your_function, your_class
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜