Relative import from parent directory and run as standalone file

I have two files in the following tree structure

├── __init__.py
├── pkg
│   ├── __init__.py
│   └── child.py
└── top.py

      

The top.py file looks like this:

variable = "I live in the top directory"

      

Child.py looks like this:

from ..top import variable

if __name__ == '__main__':
    print variable

      

If I try to run the file through python pkg/child.py

, I get an error message: ValueError: Attempted relative import in non-package

. If I run it from directory pkg

like python child.py

, I get the same error.

Reading the answers given in this answer: How do I do relative imports in Python? I tried to do python -m pkg.child

from the parent directory. Then I get the following error: ValueError: Attempted relative import beyond toplevel package

.

So I'm running out of ideas. How do you do this?

+3


source to share


3 answers


Suppose the directory containing top.py

is called foo

. Then change the current working directory to the parent tofoo

include that directory in sys.path

.

cd /path/to/parent/of/foo

      

Then run child.py

as a module:

python -m foo.pkg.child

      

gives

I live in the top directory

      




cd /path/to/foo
python -m  pkg.child

      

doesn't work as relative imports

from ..top import variable

      

refers to foo

, package, which is two directories above child.py. foo

is not recognized as a package if you sit in a directory foo

and run python -m pkg.child

.

+2


source


You can add the package-relative path to the top

search path in child.py

:



import sys
sys.path.append('../')

from top import variable

if __name__ == '__main__':
    print variable

      

+2


source


How about using a module os

? My crack inchild.py

import os

dir_path = os.path.dirname(os.path.abspath(os.curdir))
os.chdir(dir_path)

from top import variable

if __name__ == '__main__':
    print variable

      

0


source







All Articles