I have a directory which contains a bunch of function and another folder which contains my main project which I would like to be able to run from the terminal: kf_sine_demo.py
.
When I run line by line the code from VS-Code (using Shift
+ Enter
), everything works fine. In particular I can import the functions for further use:
from EKFUKF_Py import lti_disc, kf_predict, kf_update, rts_smooth
However, when I run the file from the terminal:
python kf_sine_demo.py
I get the following error:
Traceback (most recent call last):
File "EKFUKF_Py/demo/kf_sine_demo/kf_sine_demo.py", line 16, in <module>
from EKFUKF_Py import lti_disc, kf_predict, kf_update, rts_smooth
ModuleNotFoundError: No module named 'EKFUKF_Py'
I see solutions which include specifying the full path. I have strong preference for relative imports.
UPDATE:
This solution has been most useful to me: https://stackoverflow.com/a/37193862/4576194 .
python -m EKFUKF_Py.demo.kf_sine_demo.kf_sine_demo
form the parent directory of EKFUKF_Py
But, that's not quite what I want. I want to be able to run python kf_sine_demo.py
from kf_sine_demo
directory and I want it to know that the functions it needs to import are located 2 levels up.
You have to understand how python path works. This is a list of directories where python looks for the modules you try to import, you can display it uing the sys.path
command. There are a bunch of directories that python automatically add to, like path\to\your_python_install\lib
, and python also add the working directory when you run a script.
This means that when you do:
python kf_sine_demo.py
The parent directory of this file (kf_sine_demo) is added to the path, but the EKFUKF_Py
is not. Thus python can not find the modules in it.
From here, two solutions. Either you manually add this directory (which I find a little ugly, but it works):
sys.path.append("path/to/EKFUKF_Py")
Or you ensure to always run your files from the main directory, through a main.py
file, for example. from there, you will be able to call every submodule in this directory.
More here: https://www.devdungeon.com/content/python-import-syspath-and-pythonpath-tutorial
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.