JeLLyB0x3r
JeLLyB0x3r

Reputation: 328

Python Importing from Subdirectory

My file setup is like this:

main has import sub.foo, foo has import sub.bar

python main works fine. But python sub\foo doesn't work, it doesn't recognize sub in import sub.bar. I want to be able to run main as well as foo by themselves, how can I do this properly in python3.4.1?

EDIT: If I change foo to import bar, then python main says that it doesn't recognize bar in import sub.foo

Upvotes: 0

Views: 147

Answers (2)

You can use __ init__.py (without spaces)

For example, on "main/main.py" use only:

#main.py    
import sub

Create a new file with this path "main/sub/__ init__.py"

#__init__.py
import foo
import bar

Upvotes: 0

Martin Konecny
Martin Konecny

Reputation: 59571

When you run python main.py it works, because the directory of your input script is in the main/ directory, and therefore all modules are found relative to that directory.

When running foo.py directly, there is no subdirectory named sub relative to the directory of foo.py.

One workaround is to import bar since it is in the same directory as foo. However this will fail in cases where foo.py and bar.py are in separate directories.

If you want to run foo.py directly, try adding the main/ directory to your module search path. For example in foo.py:

# foo.py
import sys
import os
if __name__ == '__main__':
    foo_dir = os.path.dirname(os.path.realpath(__file__))
    parent_dir = os.path.dirname(foo_dir)
    sys.path.append(parent_dir)

import bar

Upvotes: 1

Related Questions