-2

I've got two files, foo/a.py with:

def haha():
    print("haha")

And also bar/b.py with:

import foo.a as a

I fail to run to run b.py, with:

> python bar/b.py 
Traceback (most recent call last):
  File "bar/b.py", line 1, in <module>
    import foo.a
 ImportError: No module named 'foo'

What am I doing wrong?

konr
  • 2,545
  • 2
  • 20
  • 38

2 Answers2

2

Python can only find modules on your PYTHONPATH. See this question for how to set it.

Modules can be at top level, or in a package. If you run python bar/b.py, the directory that b.py is in is implicitly added to the Python path. The directory that foo/ and bar/ are in is unknown to Python, let alone the one that contains a.py.

You can add './foo' to the PYTHONPATH. Then 'import a' will work.

If you want 'import foo.a' to work, then 'foo' must be a package, and it must be possible to find it. To do so, add '.' (the directory containing foo/' to the Pythonpath, and place an empty file named __init__.py (note that's double underscores) in the same directory as a.py. That makes foo a package, and foo.a a module in that package.

Community
  • 1
  • 1
RemcoGerlich
  • 30,470
  • 6
  • 61
  • 79
0

yes add __init__.py at ../foo/ location.

and use following :

I have directory structure like: /home/test/foo/a.py and /home/test/bar/b.py

import sys
sys.path.append('/home/test')
from foo import a
try:sys.path.remove('/home/test')
except:pass
Vivek Sable
  • 9,938
  • 3
  • 40
  • 56