简体   繁体   中英

Why I can't import module from the same directory in python

Project structure
test/
--test.py
--pkg/
----p1.py
----p2.py

test.py

import pkg.p1  
pkg.p1.print_p1()  

p1.py

import p2  
def print_p1():  
  print('in p1')  
  p2.print_p2() 

p2.py

def print_p2():  
    print('in p2')  

When I run test.py, I gets ModuleNotFoundError: No module named 'p2'.
Tried adding empty __init__.py but still no luck. Any expert can help?
Thanks in advance.

Change your p1.py file to this:

from pkg.p2 import print_p2
def print_p1():
  print('in p1')
  print_p2()

I found that adding "from.p2 import print_p2 in p1.py" into p1.py would make test.py work, though p1.py itself would have error "ImportError: attempted relative import with no known parent package".

Thanks all for your help

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