简体   繁体   中英

Why does my python import statement fail when I import this function from outside the directory?

Simple example:

File structure is:

test/lib/f1.py
test/lib/f2.py

File contents:

$ cat lib/f1.py 
from f2 import bar

def foo(a):
  print(1+bar(a))

$ cat lib/f2.py                                                                                                   
def bar(a):
  return a

So f1.py defines foo , which relies on bar , defined in f2.py .

Now, loading f1.py works just fine when inside 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

However, when loading from outside test/lib/ (say from test/ ), this fails with an import error:

$ 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)

Moving the code from f2.py in f1.py fixes the issue, but I don't want to do that.

Why am I getting this error and how can I avoid it?

Define the folder where it should look for the modules:

import sys
sys.path.append('test')

from lib.f1 import foo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM