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)
The project source directory is typically the topmost, or “root” directory that contains most of the source files. You might think of this as the “home” directory of the project. Source Insight normalizes project file names relative to this directory.
Source roots (or source folders; shown as ). These roots contain the actual source files and resources. PyCharm uses the source roots as the starting point for resolving imports. The files under the source roots are interpreted according to their type.
The project root is the folder which is the parent for all the project sources. By default, all subfolders in this folder are treated as sources and their files are involved in indexing, searching, parsing, code completion, and so on.
from pycharm>Settings>Project>Project Structure select your project and from the file tree, select your django project directory then click the blue folder Source button to define the directory as your source.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With