0

The folder is something like:

/workspace
   dosomething.py
   /pkg
      __init__.py
      a.py
      b.py

where i've added

sys.path.append('/workspace')
import a
a.func()

in dosomething.py, and

from .a import a
from .b import b

in __init__.py. And a.py imports b to use some functions in b. After running, the error is:

ModuleNotFoundError: No module named 'b'

And the error occurs when runs to import b in a.py. I want to know if i've missed some steps or there is any error in it? Thanks for any reply!

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
Yuki
  • 9
  • 1
  • 4
  • `from .b import *` will work – Jean-François Fabre Jul 22 '19 at 14:13
  • https://stackoverflow.com/questions/14132789/relative-imports-for-the-billionth-time – s3nh Jul 22 '19 at 14:15
  • @Jean-François Fabre♦ I've tried it but no work – Yuki Jul 22 '19 at 14:32
  • 1
    from pkg import a,b will work – Shreyak Jul 22 '19 at 14:32
  • "And the error occurs when runs to import b in a.py" Can you show us that import statement in a.py? – j-i-l Jul 22 '19 at 14:51
  • @yuki, which command do you start with? Is it something along the lines of `python dosomething.py`? – MultiSkill Jul 22 '19 at 14:55
  • @MultiSkill I just execute it in IDE as main – Yuki Jul 22 '19 at 15:01
  • @Shreyak it still stops at import b in a.py – Yuki Jul 22 '19 at 15:08
  • are you importing module b in a.py ? i thought u want to load modules a,b in dosomething.py. If you want to load module b in a.py then use `from pkg import b` in a.py – Shreyak Jul 22 '19 at 15:16
  • @Shreyak The problem is i want to import a in dosomething.py while a has imported b. Then the code runs till "import b" in a and reports the error. And besides I dont know if it's okay to modify a given package made by others – Yuki Jul 22 '19 at 15:24
  • best practice is not to modify other packages but create your own which does added functionality you want. In your case loading module b in a using statement `from pkg import b` in a.py and then loading module a in dosomething.py using `from pkg import a` should work – Shreyak Jul 22 '19 at 15:27
  • @jojo just simply "import b" – Yuki Jul 22 '19 at 15:30
  • @Shreyak Thanks a lot! It works. But if there exists any simplier and unified method in python to import and use a package derectly? – Yuki Jul 22 '19 at 16:22

0 Answers0