简体   繁体   English

无法从其他文件夹导入模块-python

[英]unable to import a module from different folder -python

This is the structure of my code: 这是我的代码的结构:

---root-dir/
        ----app/
            -----config/
                    ------ __init__.py
                    ------   config.py
            -----constants/
                    ------ __init__.py
                    ------ ****.py
                    ------ ****.py
            -----exception/
                    ------ __init__.py
            -----main/
                    ------ __init__.py
                    ------ controller.py
            -----util/
                    ------ __init__.py
                    ------ picklehelp.py

Now when I do the below import in /main/controller.py and run, it does not work. 现在,当我在/main/controller.py执行以下导入并运行时,它不起作用。

from app.util.picklehelp import func

How can I import the modules, without doing maximum changes in code so that it can work in any machine irrespective of the path location and OS 如何导入模块,而无需对代码进行最大程度的更改,以便无论路径位置和操作系统如何,它都可以在任何计算机上工作

The answer would be adding to the sys.path the path to your app (without the filename): 答案是将app的路径添加到sys.path中(不带文件名):

import sys
sys.path.append(r"root-dir\app\util")

from picklehelp import func

How can I import the modules, without doing maximum changes in code so that it can work in any machine* irrespective of the path location and OS 如何导入模块,而无需对代码进行最大的更改,以便它可以在任何计算机上运行*,而不管路径位置和操作系统如何

The sys module works at any operating system that Python supports. sys模块可在Python支持的任何操作系统上运行。 Then, there can be other modules indepent to an OS, like winsound , winreg or windows in the Windows operating system. 然后,可以有indepent到OS的其它模块,如winsoundwinregwindows在Windows操作系统中。

* Not any machine can run Python *并非任何机器都可以运行Python

Change your directory to root-dir. 将目录更改为root-dir。 Run python -m app.main.controller 运行python -m app.main.controller

This will run your app as a module. 这会将您的应用作为模块运行。

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

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