Import statement works on PyCharm but not from terminal

You are running foo.py like a script, but you are really using it like a module. So the proper solution is to run it as a module:

python3 -m somepackage.foo

For the record, another alternative is to edit your path like:

export PYTHONPATH=.

(Or you could put the absolute directory in there, and of course you should append any other directories that are already in your PYTHONPATH.) This is closer to what PyCharm does, but is less philosophically correct.


Setting PYTHONPATH is what makes it work, as noted above. I use the following VSCODE .env content so that it works for any project:

PYTHONPATH=${PROJ_DIR}:${PYTHONPATH}

This is essentially what PyCharm does when you check "Add Content Roots to PYTHONPATH" in your run/debug configuration. It's a helpful setting, but it spoils you because your code fails outside PyCharm.

Or, if you run in terminal, first export:

export PYTHONPATH=...

Took me days to work all this out.


i solved my problem by two steps on Linux:

  1. first step go to the root directory of your project and set:
export PYTHONPATH=$PATHONPATH:`pwd`
  1. second step run python3 -m somepackage.foo remember Without '.py' suffix