如何从同一文件夹中的模块导入功能?

新手上路,请多包涵

我试图将我的脚本分成几个带有函数的文件,所以我将一些函数移到单独的文件中,并想将它们导入一个主文件中。结构是:

 core/
  main.py
  posts_run.py

posts_run.py retrieve_posts get_all_posts 功能, get_all_posts

 from posts_run import get_all_posts

Python 3.5 给出错误:

 ImportError: cannot import name 'get_all_posts'

Main.py 包含以下几行代码:

 import vk
from configs import client_id, login, password
session = vk.AuthSession(scope='wall,friends,photos,status,groups,offline,messages',   app_id=client_id, user_login=login,
                     user_password=password)
api = vk.API(session)

然后我需要将 api 导入函数,这样我就有能力获得对 vk 的 API 调用。

完整的堆栈跟踪

Traceback (most recent call last):
  File "E:/gited/vkscrap/core/main.py", line 26, in <module>
    from posts_run import get_all_posts
  File "E:\gited\vkscrap\core\posts_run.py", line 7, in <module>
    from main import api, absolute_url, fullname
  File "E:\gited\vkscrap\core\main.py", line 26, in <module>
    from posts_run import get_all_posts
ImportError: cannot import name 'get_all_posts'

api - 是 main.py 中的 api = vk.API(session) 。 absolute_url 和 fullname 也存储在 main.py 中。我在 Windows 7 上使用 PyCharm 2016.1,在 virtualenv 中使用 Python 3.5 x64。如何导入此功能?

原文由 Oleksiy 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 567
2 个回答

您需要在核心文件夹中添加 __init__.py 。您收到此错误是因为 python 无法将您的文件夹识别为 python 包

在那之后做

from .posts_run import get_all_posts
#    ^ here do relative import
# or
from core.posts_run import get_all_posts
# because your package named 'core' and importing looks in root folder

原文由 Sardorbek Imomaliev 发布,翻译遵循 CC BY-SA 3.0 许可协议

我的文件.py:

 def myfunc():
    return 12

启动 python 解释器:

 >>> from MyFile import myFunc
>>> myFunc()
12

或者:

 >>> import MyFile
>>> MyFile.myFunc()
12

这在您的机器上不起作用吗?

原文由 Danielle M. 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题