python - 当我从目录外导入此函数时,为什么我的 python 导入语句会失败?
问题描述
简单的例子:
文件结构为:
test/lib/f1.py
test/lib/f2.py
文件内容:
$ cat lib/f1.py
from f2 import bar
def foo(a):
print(1+bar(a))
$ cat lib/f2.py
def bar(a):
return a
所以f1.py
定义foo
,它依赖于bar
,定义在f2.py
.
f1.py
现在,在里面加载就可以了test/lib/
:
$ python3
Python 3.5.2 (default, Nov 12 2018, 13:43:14)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from f1 import foo
>>> foo(1)
2
但是,当从外部加载时test/lib/
(比如 from test/
),这会失败并出现导入错误:
$ python3
Python 3.5.2 (default, Nov 12 2018, 13:43:14)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from lib.f1 import foo
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/tmp/pymod/lib/f1.py", line 1, in <module>
from f2 import bar
ImportError: No module named 'f2'
>>> Quit (core dumped)
f2.py
从in移动代码可以f1.py
解决问题,但我不想这样做。
为什么我会收到此错误,我该如何避免?
解决方案
定义应在其中查找模块的文件夹:
import sys
sys.path.append('test')
from lib.f1 import foo
推荐阅读
- android - 离开编辑文本时应用程序关闭
- javascript - d3.js:在 Angular 应用程序和 node.js 上运行相同的代码
- ios - 购买多个产品以在多个设备上使用应用程序
- powerbi - 使用 Power BI 中的度量在客户级别计算 NA
- vue.js - VueJS 组件,不能覆盖类
- android - MainActivity Kotlin Android 中未解析的符号 toInt()
- c++ - 使用指针或引用动态分配内存
- backup - rclone 使用过多的下载带宽
- json - 如果存在则从 json 返回特定值,如果不存在则返回零行
- c# - 如何 PInvoke 返回接口的 C++ 函数