0

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: enter image description here

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:

  1. Why does it show different results in PyCharm IDE and terminal?

  2. 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?

maplemaple
  • 1,297
  • 6
  • 24
  • 1
    You might want to look into [this](https://stackoverflow.com/questions/23830917/how-does-pycharm-handle-relative-imports-of-modules). The executive summary is that PyCharm does things for you, making it more error-proof, whereas running the file in terminal will not benefit from PyCharm's internal management of the system path. – Jake Tae May 15 '20 at 05:06
  • 4
    I had this too, my solution is to cd to the `python` directory (project root) and run `python -m test.test`. This is only a comment because the answer should involve something answering question 2. – bb1950328 May 15 '20 at 05:48
  • @Sadap Your method works! – maplemaple May 15 '20 at 06:44
  • 1
    @Sadap advice is good. Also my advice would be: https://stackoverflow.com/a/61698924/11138259 – sinoroc May 15 '20 at 07:28
  • pycharm does a lot of things behind it, so when you switch to the terminal, things are no longer so easy. If you must run the module file, use `python -m` – alexzshl May 15 '20 at 07:44

0 Answers0