Import statement works on PyCharm but not from terminal

后端 未结 3 1139
清歌不尽
清歌不尽 2020-12-03 09:25

Pycharm 2016.2.3, Mac OS X 10.11.1, Python 3.5 (Homebrew);

I have this folder structure

project
  /somepackage
    /subpackage
     __init__.py   
           


        
相关标签:
3条回答
  • 2020-12-03 10:05

    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.

    0 讨论(0)
  • 2020-12-03 10:08

    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
    0 讨论(0)
  • 2020-12-03 10:10

    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.

    0 讨论(0)
提交回复
热议问题