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?
source to share
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
.
source to share