将文件夹添加到 Python 库路径,一劳永逸 (Windows)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20394613/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 20:19:34  来源:igfitidea点击:

Add a folder to the Python library path, once for all (Windows)

pythonpathenvironment-variablesanaconda

提问by Basj

I use

我用

sys.path.append('D:/my_library_folder/')
import mymodule

in order to import some module.

为了导入一些模块。

How to add permanentlythis folder D:/my_library_folder/to the Python library path, so that I will be able to use only

如何将此文件夹永久添加D:/my_library_folder/到 Python 库路径中,以便我只能使用

import mymodule

in the future?

在将来?

(Even after a reboot, etc.)

(即使在重新启动等之后)

采纳答案by suhailvs

just put the folder in site-packagesdirectory. ie:

只需将文件夹放在site-packages目录中。IE:

C:\PythonXY\Lib\site-packages

Note: you need to add an empty file __init__.pyto the folder

注意:您需要__init__.py在文件夹中添加一个空文件



Files named __init__.pyare used to mark directories on disk as a Python package directories.

命名__init__.py的文件用于将磁盘上的目录标记为 Python 包目录。

If you have the files:

如果您有以下文件:

C:\PythonXY\Lib\site-packages\<my_library_folder>\__init__.py
C:\PythonXY\Lib\site-packages\<my_library_folder>\module.py

you can import the code in module.py as:

您可以将 module.py 中的代码导入为:

from <my_library_folder> import module

If you remove the __init__.pyfile, Python will no longer look for submodules inside that directory, so attempts to import the module will fail.

如果删除该__init__.py文件,Python 将不再在该目录中查找子模块,因此尝试导入模块将失败。

If you have lots of folders, then create the empty __init__.pyfile in each folder. for eg:

如果您有很多文件夹,则__init__.py在每个文件夹中创建空文件。例如:

C:\PythonXY\Lib\site-packages\<my_library_folder>\
    __init__.py
    module.py        
    subpackage\
        __init__.py
        submodule1.py
        submodule2.py

回答by weisert

Set PYTHONPATH environment variable to D:/my_library_folder/

将 PYTHONPATH 环境变量设置为 D:/my_library_folder/

回答by aquavitae

If D:/my_library_folderis a project you're working on and has a setup script, you could also do python setup.py develop. Not entirely related to the question, but I also recommend using virtualenv.

如果D:/my_library_folder是您正在处理的项目并且有安装脚本,您也可以执行python setup.py develop. 与问题不完全相关,但我也建议使用virtualenv