python - 尝试在非包中进行相对导入

标签 python python-import python-module

我的项目结构如下:

+main_proj

    +modules
        +user_ops
            -add_user.py
            -remove_user.py
            -__init.py
    +common
        -user_operations.py
        -__init__.py
    -main.py
    -__init__.py

我的问题是 add_user.pyremove_user.py 都依赖于 user_operations 并且当我尝试调用它们时,我得到一个非包中的相对导入错误。

主.py

from common import user_operations as user_operations  #This works ok

if __name__ == '__main__':

    command = "remove_user"

    #Load usage, functions and paths to modules
    __doc__, function_dictionary, modules = utilities.load_modules()

    #Get function from dictionary
    func = function_dictionary[command]

    #Execute function
    result = func(api_root, arguments, simulate, headers)

func(api_root, arguments, simulate, headers) 调用的模块

remove_user_front.py

from ...common import user_operations as user_operations

    def remove_user_front(api_root, arguments, simulate, headers):

        #Get users in this account
        users = user_operations.get_users(api_root, arguments["<source_account>"], headers)

        #This is smelly
        if arguments["--id"]:
            type = "id"
        elif arguments["--username"]:
            type = "username"
        #End smell

        result = remove_user(api_root, arguments["<source_account>"], arguments["<user_id>"], type, simulate, headers)

        if not result:
            return False
        else:
            return True

    function_dictionary = {"remove_user" : remove_user_front}

错误:

Traceback (most recent call last):
  File "C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\Extensio
ns\Microsoft\Python Tools for Visual Studio\2.0\visualstudio_py_util.py", line 7
6, in exec_file
    exec(code_obj, global_variables)
  File "C:\Users\mryan\Documents\Code\cli\cli_front.py", line
 70, in <module>
    recovery.start_recovery(recovery_file, auto_recovery, headers, modules)
  File "C:\Users\mryan\Documents\Code\cli\recovery.py", line 1
01, in start_recovery
    imported_module = imp.load_source('recovery',module)
  File "C:\Users\mryan\Documents\Code\cli\modules\cam_ops\
remove_user_front.py", line 1, in <module>
    from ...common import user_operations as user_operations
ValueError: Attempted relative import in non-package

有人知道如何保持我的文件结构并使 modules 下的模块能够使用 common 下的模块吗?

最佳答案

当您的应用程序启动时,它会获得一个 os.path 属性。

每个尝试导入任何内容的模块都将具有相同的路径。这意味着需要从 user_ops 导入某些内容的公共(public)文件将需要导入它,就像导入它们的 main.py 一样。

尝试

from modules.user_ops import add_user

在你的 user_operations 中

关于python - 尝试在非包中进行相对导入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21556973/

相关文章:

python - "Map"Python 中的嵌套列表

python - 为已存在的 dash 子应用程序导入包

python - 测试期间Django双重导入

python - 如何覆盖模块名称(__name__)?

python - 如何从不同的文件夹导入模块?

python - 通过函数调用与 Python 3.4 多处理中的 Process 进行通信

python - 如何用包含字符串值的列表填充 Pandas 数据框列

python - Django 图像未上传

python - 缩短深度导入/长命名空间

python - 将字符串传递给模块 "once"