从同一目录“未解析的引用”导入模块

时间:2018-06-21 02:11:42

标签: python pycharm setuptools

更新:找到了answer


如何从classmodule导入MyClass?

目录结构:

/project
  /datagenerator
    __init__.py
    __main__.py
    classmodule.py
    setup.py

运行该程序:python datagenerator

Traceback (most recent call last):
  File "C:\Users\Matt\AppData\Local\Programs\Python\Python36-32\lib\runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "C:\Users\Matt\AppData\Local\Programs\Python\Python36-32\lib\runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "datagenerator\__main__.py", line 2, in <module>
    from .classmodule import MyClass
ImportError: attempted relative import with no known parent package

__ main __。py 导入MyClass

import sys
from .classmodule import MyClass
from .funcmodule import my_function


def main():
    print('in main')
    args = sys.argv[1:]
    print('count of args :: {}'.format(len(args)))
    for arg in args:
        print('passed argument :: {}'.format(arg))
    my_function('hello world')
    my_object = MyClass('Thomas')
    my_object.say_name()


if __name__ == '__main__':
    main()

我尝试过:

from classmodule import MyClass

尽管__main__.py和classmodule位于同一目录中,但仍存在未解析的引用

Unresolved reference 'classmodule'

2 个答案:

答案 0 :(得分:0)

代码中的import语法无效。相反,请尝试以下操作:

from classmodule import MyClass
from funcmodule import my_function

答案 1 :(得分:0)

您的文件结构应如下所示:

目录结构:

__init__.py file_a.py file_b.py

哦,很抱歉过去的答案,请继续将其命名为__main__.py

存在from . import foo文件时,您需要from . import *__init__.py。然后,您可以从同一文件夹导入任何内容。