Answer a question

In Pycharm, if you right click in a folder inside your project, you can mark it as sources root, so then you can import modules from this folder and subfolders.

However doing it this way will only make your program runnable inside Pycharm, if I try to execute from outside Pycharm (eg from the console) it will complain that certain modules are not found, which is the problem that I'm facing.

If I mark a certain folder as sources root my program runs fine, but I need to understand what does it do so I can configure the program to find this modules even if not using Pycharm.

I want to know what does this option exactly do, and how can I get the same behaviour without using it.

It is just adding a __init__.py file in the root folder? Is it doing something like:

import sys
sys.path.insert(0, my_folder)

Answers

First __init__.py marks a directory as a regular package directory(this is pre 3.3, in 3.3+ its not required anymore). With this, python will look for submodules inside that directory for imports.

"Mark directory as sources root" sets the PATH(or PYTHONPATH) for the environment. In shell, it will be like,

export PYTHONPATH="${PYTHONPATH}:/your/source/root"

PYTHONPATH holds the default search path for module files. This will enable the interpreter to search for the modules in the appended path. The default value is installation dependent(normally it contains path to Python binaries).

You can also manipulate this search path using sys.path from inside a python file.

Logo

学AI,认准AI Studio!GPU算力,限时免费领,邀请好友解锁更多惊喜福利 >>>

更多推荐