Why I can import the package in the parent directory in PyCharm, however, it reports an error in the terminal?
I will use the following toy code to show my problem. For example, the project structure is like the following:
In hello.py
is:
def func():
print("hello")
In test.py
is
import mypackage.hello
mypackage.hello.func()
Now if I run test.py
in PyCharm, it runs perfectly and prints hello
. However, if I use the terminal and cd
to test
directory, and run command python test.py
, it reports the following error:
Traceback (most recent call last):
File "test/test.py", line 1, in <module>
import mypackage.hello
ModuleNotFoundError: No module named 'mypackage'
PS: I use the same environment in both PyCharm and terminal.
Question:
Why does it show different results in PyCharm IDE and terminal?
In general, what's the correct style to import a package in the parent directory such that I can run both in the terminal and IDE?