【问题标题】:Importing modules within the same directory在同一目录中导入模块
【发布时间】:2017-08-06 23:22:13
【问题描述】:

考虑以下目录结构:

lib/
  markov.py
  solver.py
  test.py

markov.py 具有以下代码:super() throwing an error in Sublime Text, works in PyCharm/Terminal

solver.py 只包含一堆数学函数,这里有一个例子:

def mm1_busy_idle(arrival, service):
    return round(1 - (arrival / service), 4)

现在,当我尝试在 markov.py 中执行 import solver 时,PyCharm 告诉我有 No module named solver。但是,当我执行import test 时,它做得很好,我可以从那里运行测试功能:

def test():
    print("test!")

此外,当我将鼠标悬停在 test.test() 上时,PyCharm 会显示以下工具提示:Cannot find reference 'test' in '__init__.py'

我的问题是:为什么我可以import test 并运行函数test() 但我不能在markov.py 中运行import solver

【问题讨论】:

  • 试试from . import solver
  • @yosemite_k SystemError: Parent module '' not loaded, cannot perform relative import
  • from lib import solver
  • @yosemite_k 这给了我unresolved reference

标签: python


【解决方案1】:

在lib中添加一个文件(__init__.py空文件),

lib/
  __init__.py
  markov.py
  solver.py
  test.py

终极解决方案:

import sys
sys.path.append("/path/to/lib")

【讨论】:

  • 您提出的解决方案并没有真正改变太多。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-11-16
  • 2021-09-24
  • 2018-12-27
  • 1970-01-01
  • 1970-01-01
  • 2021-10-11
相关资源
最近更新 更多