python3 - Import python file as module
Peter Otten
__peter__ at web.de
Mon May 18 10:57:29 EDT 2020
shivani.shinde at alefedge.com wrote:
> Hi,
> I am a beginner to Python. I want to achieve the following:
>
> My directory structure:
>
> a
> └── b
> └── c
> ├── p
> │ └── q
> │ └── test.py
> └── x
> └── y
> └── run.py
>
> In my run.py file, I want to import everything from test.py(contains
> methods).
>
> I have found relative path for test.py as "....p.q".
> I tried with exec() to import as : exec("from ....p.q import *"),
> but this gives me >> "list out of index" error.
I do not recognize that error. Is this cut-and-paste?
> Then I tried with importlib.import_module with various combinations such
> as: 1. importlib.import_module('.test', package="....p.q")
> 2. importlib.import_module('test', package="....p.q")
> 3. importlib.import_module('....p.q.test', package=None)
Why are you trying import_module() or exec() when you know the location of
the module you want to import?
> But I end up getting error as >> No module found "".
>
> Can anyone help me with this situation?
You need to make sure that a is in your sys.path and that the importing
module is itself imported using the complete path. For example:
Given
$ tree
.
└── a
└── b
└── c
├── p
│ └── q
│ └── test.py
└── x
└── y
└── run.py
7 directories, 2 files
$ cat a/b/c/p/q/test.pydef hello():
print("Hello, world!")
$ cat a/b/c/x/y/run.py
from ...p.q.test import hello
hello()
you can run your run.py with
$ python3 -m a.b.c.x.y.run
Hello, world!
but not with
$ python3 a/b/c/x/y/run.py
Traceback (most recent call last):
File "a/b/c/x/y/run.py", line 1, in <module>
from ...p.q.test import hello
SystemError: Parent module '' not loaded, cannot perform relative import
because here run.py is a standalone script from Python's point of view
rather than part of a package hierarchy.
In general you can never go higher than the toplevel package, so this also
fails:
$ cd a/b/c
$ python3 -m x.y.run
Traceback (most recent call last):
File "/usr/lib/python3.4/runpy.py", line 170, in _run_module_as_main
"__main__", mod_spec)
File "/usr/lib/python3.4/runpy.py", line 85, in _run_code
exec(code, run_globals)
File "/home/petto/srcx/clpy/shivani/a/b/c/x/y/run.py", line 1, in <module>
from ...p.q.test import hello
ValueError: attempted relative import beyond top-level package
While this works
$ cd ..
$ python3 -m c.x.y.run
Hello, world!
it is a good idea to decide on the root package once and for all, and then
only import starting from that.
More information about the Python-list
mailing list