【问题标题】:import filename is greyed out导入文件名是灰色的
【发布时间】:2019-09-30 09:54:58
【问题描述】:

我正在使用 PyCharm 开发一个项目,我有两个文件:connect.py 和 run.py。这两个文件都在项目目录的根目录下。

connect.py

"""Hello Analytics Reporting API V4."""

from apiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials


SCOPES = ['https://www.googleapis.com/auth/analytics.readonly']
KEY_FILE_LOCATION = 'client_secrets.json'
VIEW_ID = '123456' # My actual view ID is here


def initialize_analyticsreporting():
  """Initializes an Analytics Reporting API V4 service object.

  Returns:
    An authorized Analytics Reporting API V4 service object.
  """
  credentials = ServiceAccountCredentials.from_json_keyfile_name(
      KEY_FILE_LOCATION, SCOPES)

  # Build the service object.
  analytics = build('analyticsreporting', 'v4', credentials=credentials)

  return analytics

运行.py

import connect

# some more code here...

第一行,import connect 是灰色的:

当我将鼠标悬停在灰色文本上时,会出现一个弹出“未使用的导入语句”,并带有一个可点击的“更多操作”选项:

这将打开一个带有错误警告的“检查结果”窗格。详情见屏幕。

connect.py 内部的代码最初位于 run.py 的顶部,我只是想分成两个脚本。当它们都在同一个文件中时,脚本运行良好。只有当我分成两个文件时才会发生这种情况。

如何将 connect.py 导入 run.py?让我知道是否需要提供更多详细信息?

【问题讨论】:

    标签: python pycharm


    【解决方案1】:

    如果导入整个模块,请确保使用点运算符 ex.foo.bar

    如果使用 python

    您需要创建一个空白的__init__.py 文件,以便python 知道您所在的目录应该被视为python 包。

    在此答案中查看更多信息here

    【讨论】:

    • 您好,感谢您的提示。我添加了一个空文件 init.py 但没有发生或改变。我注意到您分享评论的链接:Update: The file __init__.py was required under Python 2.X and is still required under Python 2.7.12 (I tested it) but it is no longer required from (allegedly) Python 3.3 onwards, and is not required under Python 3.4.3 (I tested it). See stackoverflow.com/questions/37139786 for more details. – Rob_before_edits 我正在使用 Python3.7
    • 嗯,好点。您是否尝试过仅导入所需的功能?喜欢from foo import bar 或者你可以试试from foo import *
    • 嗨乔希。是的,这似乎确实有效!但是,最好了解我如何/为什么不能只使用import connect。我会在此期间运行,但问题未解决
    • @DougFir 所以经过更多挖掘后,我找到了this。所以看起来你需要告诉 pycharm 哪个目录包含你的项目文件。
    • 我偶然发现了这个问题。我需要首先使用connect.somemethod 在整个脚本中引用连接方法,否则 PyCharm 只会将其变灰。我是直接调用方法而不是在它们前面加上connect.
    猜你喜欢
    • 1970-01-01
    • 2019-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-11
    相关资源
    最近更新 更多