“将目录标记为源根目录"是什么意思?真的吗? [英] What does "Mark directory as sources root" really do?

查看:41
本文介绍了“将目录标记为源根目录"是什么意思?真的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Pycharm中,如果你在你的项目中右键单击一个文件夹,你可以将它标记为sources root,这样你就可以从这个文件夹和子文件夹中导入模块了.

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.

但是这样做只会使您的程序在 Pycharm 内部运行,如果我尝试从 Pycharm 外部执行(例如从控制台),它会抱怨找不到某些模块,这是我面临的问题.

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.

如果我将某个文件夹标记为源根目录,我的程序运行良好,但我需要了解它的作用,以便即使不使用 Pycharm,我也可以配置程序以查找此模块.

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.

它只是在根文件夹中添加一个 __init__.py 文件?它是否在做类似的事情:

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)

推荐答案

首先 __init__.py 将目录标记为常规包目录(这是 3.3 之前的,在 3.3+ 中不再需要).这样,python 将在该目录中查找子模块以进行导入.

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.

将目录标记为源根目录"为环境设置 PATH(或 PYTHONPATH).在 shell 中,它会像,

"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 保存模块文件的默认搜索路径.这将使解释器能够搜索附加路径中的模块.默认值取决于安装(通常它包含 Python 二进制文件的路径).

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).

您还可以在 python 文件中使用 sys.path 操作此搜索路径.

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

这篇关于“将目录标记为源根目录"是什么意思?真的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆