我的项目有以下结构:
+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.py
和remove_user.py
都依赖于user_operations
,当我试图调用它们时,会得到一个relative import in non-package
错误。
Main.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)
调用的模块
删除用户前端.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中导入某些内容的公共文件将需要像导入main.py一样导入。
试试看
在用户操作中
相关问题 更多 >
编程相关推荐