简体   繁体   中英

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. I created a .pth file and add my root path of the file in my site-packages folder. 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). 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. But I just believe that Python will provide a more efficient way to achieve that.

I haven't had occasion to ever use a .pth file. I prefer a two-pronged approach:

  • Use a shebang which runs env python , so it uses the first python on your path, ie:

#!/usr/bin/env python

  • Use virtualenv to keep separate different environments and group the necessary libraries for any given program/program set together. This has the added benefit that the requirements file (from pip freeze output) can be stored in source control, and the environment can be recreated easily anywhere, such as for use with Jenkins tests, et al.

In the virtualenv case the python interpreter can be explicitly invoked from the virtualenv 's bin directory.

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

Edit with response to comment from 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM