我试图将我的脚本分成几个带有函数的文件,所以我将一些函数移动到单独的文件中,并希望将它们导入到一个主文件中。结构是:
core/
main.py
posts_run.pyposts_run.py有两个函数,get_all_posts和retrieve_posts,因此我尝试使用以下命令导入get_all_posts:
from posts_run import get_all_postsPython 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)。全名和全名也存储在main.py中。我在Windows7上使用PyCharm 2016.1,在virtualenv中使用Python3.5 x64。如何导入此函数?
发布于 2016-08-31 00:58:02
您需要在核心文件夹中添加__init__.py。出现此错误是因为python无法将您的文件夹识别为python package
在那之后做
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发布于 2016-08-31 01:00:39
MyFile.py:
def myfunc():
return 12启动python解释器:
>>> from MyFile import myFunc
>>> myFunc()
12或者:
>>> import MyFile
>>> MyFile.myFunc()
12这在你的机器上不起作用吗?
发布于 2016-08-31 01:19:19
可以从这个问题中找到作弊的解决方案(问题是Why use sys.path.append(path) instead of sys.path.insert(1, path)? )。从本质上讲,您可以执行以下操作
import sys
sys.path.insert(1, directory_path_your_code_is_in)
import file_name_without_dot_py_at_end这将解决当你在PyCharm 2016.1中运行它时,它可能在不同的当前目录中,而不是你所期望的……
https://stackoverflow.com/questions/39233077
复制相似问题