[英]How to use PYTHONPATH to import the whole folder in Python
I am new to python and trying to add a project folder to the PYTHONPATH. 我是python的新手,正在尝试将项目文件夹添加到PYTHONPATH。 I created a .pth file and add my root path of the file in my site-packages folder.
我创建了一个.pth文件,并将该文件的根路径添加到我的site-packages文件夹中。 However, when I trying to import the .py files in this folder, only those located under the root folder (for example '/sample') can be imported, but those subfolders under the /sample folder were not able to be imported (for example /sample/01).
但是,当我尝试在此文件夹中导入.py文件时,只能导入位于根文件夹下的文件(例如'/ sample'),但无法导入/ sample文件夹下的那些子文件夹(对于例如/ sample / 01)。 So my question is what file and how to change it to make my whole folder including all its subfolders can be importable.
所以我的问题是,什么文件以及如何更改它以使包括所有子文件夹在内的整个文件夹都可以导入。
In the worst case I can think of is to write down all the folders name in the .pth file in site-packages. 在最坏的情况下,我想到的是在站点包中记下.pth文件中的所有文件夹名称。 But I just believe that Python will provide a more efficient way to achieve that.
但是我只是相信Python将提供更有效的方法来实现这一目标。
I haven't had occasion to ever use a .pth file. 我从来没有机会使用过.pth文件。 I prefer a two-pronged approach:
我更喜欢两种方法:
#!/usr/bin/env python
In the virtualenv case the python interpreter can be explicitly invoked from the virtualenv 's bin directory. 在virtualenv的情况下,可以从virtualenv的bin目录中显式调用python解释器。
For local modules in this case, a local PyPI server can be used to centralize custom modules, and they can also be included in the requirements file (via the --extra-index option of pip ). 对于这种情况下的本地模块,可以使用本地PyPI服务器集中自定义模块,它们也可以包含在需求文件中(通过pip的--extra-index选项)。
Edit with response to comment from OP: 编辑并回复OP的评论:
I have not used SublimeREPL before, however, based on the scenario you have described, I think the overall simplest approach might be to simply symlink the directories into your site-packages (or dist-packages , as the case may be) directory. 我以前没有使用SublimeREPL ,但是,根据您所描述的情况,我认为总体上最简单的方法可能是将目录符号链接到您的site-packages (或dist-packages ,视情况而定)目录中。
It's not an ideal scenario for a production server, but for your purposes, on a client box, I think it would be fine. 对于生产服务器而言,这不是理想的方案,但是出于您的目的,在客户端盒上,我认为这很好。 If you don't want to have to use the folder name, ie
import ch1/foo
, you'll need to symlink inside of those directories so you can simply import foo
. 如果您不想使用文件夹名称,即
import ch1/foo
,则需要在这些目录内进行符号链接,以便只需import foo
。 If you're OK with using the dir name, ie import ch1/foo
, then you should only need to symlink the top-level code directory. 如果可以使用目录名,即
import ch1/foo
,则只需要符号链接顶级代码目录。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.