但在导入此模块时会中断

但在导入此模块时会中断

本文介绍了Python导入在运行模块时有效,但在导入此模块时会中断的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的目录结构:

source\
  main\
    bar.py
    run.py
  A\
    foo.py

bar.py 有需要 foo.py 的函数,所以我从吧使用导入* ,这是有效的,因为我给了 foo.py 找到 bar.py的正确路径。我通过运行 foo.py 并通过 bar.py 调用任何函数来验证这一点,而不附加 bar 旁边。例如,如果 myFun bar.py 中定义,我只需调用 myFun( ...) in foo.py 。到目前为止,这一切都很有效。

bar.py has functions which foo.py needs, so I use from bar import *, which works, as I've given foo.py the correct path to find bar.py. I verify this by running foo.py and calling any of the functions from bar.py without appending bar next to it. For example, if myFun is defined in bar.py, I can simply call myFun(...) in foo.py. This works all great so far.

run.py 进口 foo.py 。但是,当我尝试从 foo.py 运行一个函数时,它又使用从 bar.py 导入的函数,Python声称 myFun(...)不存在。请注意, myFun 最初是在 bar.py 中定义的。

run.py imports foo.py. However, when I try to run a function from foo.py which in turn uses a function imported from bar.py, Python claims myFun(...) does not exist. Note that myFun was originally defined in bar.py.

NameError:全局名称'myFun'未定义

我设法解决此问题的唯一方法是将 myFun 复制到 foo.py 中,但这不是真正的解决方案。

The only way I managed to resolve this was to copy myFun into foo.py, but that is not really a solution.

推荐答案

只要你有其他选择,就应该避免摆弄导入路径。在这种情况下,创建空文件 main \ _init __。py A\__init __。py 以便Python识别这些目录作为包,在 foo.py main.bar 替换 bar $ c>并从顶部源目录运行它。

You should avoid fiddling with the import paths as long as you have other options. In this case, create empty files main\__init__.py and A\__init__.py so Python recognizes these directories as packages, replace bar with main.bar in foo.py and run it from the top source directory.

现在,将函数从 foo.py 导入到 run.py 应该像以下一样简单:

Now, importing functions from foo.py to run.py should be as easy as:

from A.foo import fooFun1, fooFun2

这篇关于Python导入在运行模块时有效,但在导入此模块时会中断的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 11:10