Why are my imports failing when running from command line while imports succeed if running from PyCharm?

771 Views Asked by At

I get "ModuleNotFoundError: No module named "

A little background:

1) My venv is using python 3.6.9

2) Already tried adding the folders to PYTHONPATH via sys.path.append

3) Heirarchy, or the relevant part:

/project folder

|--folder A

  |--__init__.py
  |--a.py

|--folder B

  |--__init__.py
  |--b.py

|--init.py

I am trying to import from a.py to b.py Tried it in various ways-

1) import b

2) from b import x

Would really appreciate some help, been on this for some time now.

1

There are 1 best solutions below

3
AudioBubble On BEST ANSWER

Why?

Because you run your script differently. When you run it with PyCharm then PyCharm adds project directory and all the sourse directories to sys.path. That's why import A.a works. However when you run your script with console command then only file location is added to sys.path. Just print sys.path to see what it contains.

To solve the issue you may use various approaches.

Easiest way is to use PYTHONPATH. For example, on Windows you can run command set PYTHONPATH=[project_folder];%PYTHONPATH% then import A.a works. Or you can run slightly different version set PYTHONPATH=[project_folder/A];%PYTHONPATH% then import a works. Basically this command adds directory to sys.path.

Alternative solution is to have main function in b.py and some launching_script.py in project_folder. Instead of running b.py you run your launching_script.py. Thus you always have project directory in sys.path. So absolute imports starting with project directory (like import A.a) will work in both PyCharm and console.

Another approach is some ugly code like the following one:

try:
    import A.a as module_a
except ModuleNotFoundError:
    import pathlib
    import sys
    sys.path.append(str(pathlib.Path(__file__).parent.parent))
    import A.a as module_a

Also you may use relative imports. A little harder, less readable and error-prone way demanding some work on the project structure.