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

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

问题描述

在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).在外壳中,就像

"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天全站免登陆