How PyCharm imports differently than system command prompt (Windows)

From [Python.Docs]: Command line and environment – PYTHONPATH:

Augment the default search path for module files. The format is the same as the shell’s PATH: one or more directory pathnames separated by os.pathsep (e.g. colons on Unix or semicolons on Windows). Non-existent directories are silently ignored.

You can also find more details on [SO]: Strange error while using Pycharm to debug PyQt gui (@CristiFati’s answer).

So, in order for Python to be able to load a module (package) without specifying its path, the path must be present in %PYTHONPATH% environment variable.

You mentioned %PATH% several times in the question but it’s %PYTHONPATH% (MyCode must be added to it).

PyCharm does that because of (any of) the 2 checkboxes in the image below (dialog can be triggered from the menu: Run -> Edit Configurations…):

Img0

If you want to get things working from CmdLine, yo have to do the same thing there as well:

[cfati@CFATI-5510-0:e:\Work\Dev\StackOverflow\q054955891\DiscordBot]> sopr.bat
### Set shorter prompt to better fit when pasted in StackOverflow (or other) pages ###

[prompt]> set py
Environment variable py not defined

[prompt]> "e:\Work\Dev\VEnvs\py_064_03.06.08_test0\Scripts\python.exe" DiscordBot.py
Traceback (most recent call last):
  File "DiscordBot.py", line 1, in <module>
    from UsefulFunctions.Messaging import Texter
ModuleNotFoundError: No module named 'UsefulFunctions'

[prompt]> set PYTHONPATH=e:\Work\Dev\StackOverflow\q054955891

[prompt]> set py
PYTHONPATH=e:\Work\Dev\StackOverflow\q054955891

[prompt]> "e:\Work\Dev\VEnvs\py_064_03.06.08_test0\Scripts\python.exe" DiscordBot.py
e:\Work\Dev\StackOverflow\q054955891\UsefulFunctions\Messaging\Texter.py imported

Conversely, in PyCharm (with the content roots related checkbox from above, checked), more content roots can be added like in the image below (menu: File -> Settings…, select Project Structure then Add Content Root):

Img1

This is useful when some required modules are located deeper in the project tree (and some dirs aren’t valid Python package names).

So, when dealing with this type of situation, checking [Python.Docs]: sys.path, [Python.Docs]: os.getcwd() and module path, can save lots of wasted time and headaches:

import os
import sys

print(sys.path)
print(os.getcwd())

import some_module
print(some_module)

As a side note, I personally hate names starting with My (e.g. MyCode). Such a name tells me that the purpose of whatever entity “wears” it, was not clear to the person who wrote the code. Try finding a more useful name (e.g. TestBotProject, or smth similar) :).

[SO]: PyCharm doesn’t recognize installed module (@CristiFati’s answer) might also contain some useful info.

Leave a Comment