0

My file setup is like this:

  • main/main.py
  • main/sub/foo.py
  • main/sub/bar.py

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

3
  • 3
    foo should import bar, since it's in the same directory. Commented Jun 10, 2015 at 19:53
  • You never need to use backslashes for pathname separation. Even MSDOS and Windows allow normal (forward) slashes. By always using forward slashes, you won't accidentally specify a formfeed (\f) as you might be here. Commented Jun 10, 2015 at 20:00
  • wallyk, my mistake when writing this up. I always autocomplete with tab in my terminal and puts the correct slash in for me, so I don't usually use backslashes for pathname separation. Didn't know about the formfeed though, thanks! Commented Jun 10, 2015 at 20:07

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.