问题:将目录永久添加到PYTHONPATH?

每当我使用时sys.path.append,都会添加新目录。但是,一旦我关闭python,列表将恢复为以前的值(默认值)。如何将目录永久添加到PYTHONPATH

Whenever I use sys.path.append, the new directory will be added. However, once I close python, the list will revert to the previous (default?) values. How do I permanently add a directory to PYTHONPATH?


回答 0

您需要将新目录添加到环境变量中PYTHONPATH,并用冒号与其之前的内容分隔开。在任何形式的Unix中,您都可以在启动脚本中执行此操作,该脚本适合于您正在使用的任何shell(.profile或取决于您喜欢的shell),该命令又取决于所讨论的shell。在Windows中,您可以为此目的通过系统GUI进行操作。

superuser.com 可能是一个更好的地方,例如,如果您需要有关如何在所选平台和外壳程序中丰富环境变量的详细信息,请提供更多详细信息,因为这本身并不是真正的编程问题。

You need to add your new directory to the environment variable PYTHONPATH, separated by a colon from previous contents thereof. In any form of Unix, you can do that in a startup script appropriate to whatever shell you’re using (.profile or whatever, depending on your favorite shell) with a command which, again, depends on the shell in question; in Windows, you can do it through the system GUI for the purpose.

superuser.com may be a better place to ask further, i.e. for more details if you need specifics about how to enrich an environment variable in your chosen platform and shell, since it’s not really a programming question per se.


回答 1

如果您正在使用bash(在Mac或GNU / Linux发行版上),请将其添加到您的 ~/.bashrc

export PYTHONPATH="${PYTHONPATH}:/my/other/path"

If you’re using bash (on a Mac or GNU/Linux distro), add this to your ~/.bashrc

export PYTHONPATH="${PYTHONPATH}:/my/other/path"

回答 2

除了操作之外,PYTHONPATH您还可以创建路径配置文件。首先找出Python在哪个目录中搜索此信息:

python -m site --user-site

由于某些原因,这似乎在Python 2.7中不起作用。在那里您可以使用:

python -c 'import site; site._script()' --user-site

然后.pth在该目录中创建一个文件,其中包含您要添加的路径(如果目录不存在,则创建该目录)。

例如:

# find directory
SITEDIR=$(python -m site --user-site)

# create if it doesn't exist
mkdir -p "$SITEDIR"

# create new .pth file with our path
echo "$HOME/foo/bar" > "$SITEDIR/somelib.pth"

Instead of manipulating PYTHONPATH you can also create a path configuration file. First find out in which directory Python searches for this information:

python -m site --user-site

For some reason this doesn’t seem to work in Python 2.7. There you can use:

python -c 'import site; site._script()' --user-site

Then create a .pth file in that directory containing the path you want to add (create the directory if it doesn’t exist).

For example:

# find directory
SITEDIR=$(python -m site --user-site)

# create if it doesn't exist
mkdir -p "$SITEDIR"

# create new .pth file with our path
echo "$HOME/foo/bar" > "$SITEDIR/somelib.pth"

回答 3

这适用于Windows

  1. 在Windows上,对于Python 2.7,请转到Python设置文件夹。
  2. 打开库/站点包。
  3. 将example.pth空文件添加到此文件夹。
  4. 将所需的路径添加到文件,每行一个。

然后,您将能够从脚本中查看这些路径内的所有模块。

This works on Windows

  1. On Windows, with Python 2.7 go to the Python setup folder.
  2. Open Lib/site-packages.
  3. Add an example.pth empty file to this folder.
  4. Add the required path to the file, one per each line.

Then you’ll be able to see all modules within those paths from your scripts.


回答 4

如果仍然有人困惑-如果您使用的是Mac,请执行以下操作:

  1. 打开终端
  2. 类型 open .bash_profile
  3. 在弹出的文本文件中,在最后添加以下行: export PYTHONPATH=$PYTHONPATH:foo/bar
  4. 保存文件,重新启动终端,然后完成

In case anyone is still confused – if you are on a Mac, do the following:

  1. Open up Terminal
  2. Type open .bash_profile
  3. In the text file that pops up, add this line at the end: export PYTHONPATH=$PYTHONPATH:foo/bar
  4. Save the file, restart the Terminal, and you’re done

回答 5

您可以通过pythonrc文件添加路径,该文件在Linux上默认为〜/ .pythonrc。即。

import sys
sys.path.append('/path/to/dir')

您也可以PYTHONPATH在全局rc文件中(例如~/.profile在Mac或Linux上)或通过Windows上的“控制面板”->“系统”->“高级”选项卡->“环境变量”来设置环境变量。

You could add the path via your pythonrc file, which defaults to ~/.pythonrc on linux. ie.

import sys
sys.path.append('/path/to/dir')

You could also set the PYTHONPATH environment variable, in a global rc file, such ~/.profile on mac or linux, or via Control Panel -> System -> Advanced tab -> Environment Variables on windows.


回答 6

为了提供更多说明,Python将使用脚本(通常位于sys.prefix + 和中)自动构建其搜索路径(如上所述此处)。一个可以获得sys.prefix的值:site.pylib/python<version>/site-packageslib/site-python

python -c 'import sys; print(sys.prefix)'

然后,site.py脚本将取决于平台的许多目录(例如/usr/{lib,share}/python<version>/dist-packages)添加/usr/local/lib/python<version>/dist-packages到搜索路径,并且还在这些路径中<package>.pth搜索包含特定其他搜索路径的配置文件。例如,easy-install维护其已安装软件包的集合,这些软件包已添加到系统特定文件中,例如在Ubuntu上/usr/local/lib/python2.7/dist-packages/easy-install.pth。在典型的系统上,有很多这些.pth文件,它们可以解释sys.path中一些意外的路径:

python -c 'import sys; print(sys.path)'

因此,可以创建一个.pth文件并将其放置在任何这些目录中(包括如上所述的sitedir )。这似乎是大多数软件包被添加到sys.path的方式,而不是使用PYTHONPATH。

注意:在OSX上,site.py为’framework builds’添加了一个特殊的附加搜索路径(但似乎适用于python的常规命令行使用):(/Library/Python/<version>/site-packages例如,对于Python2.7:)/Library/Python/2.7/site-packages/,这是应该使用第三方软件包的地方要安装(请参阅该目录中的自述文件)。因此,可以在其中添加包含其他搜索路径的路径配置文件,例如创建一个名为的文件/Library/Python/2.7/site-packages/pip-usr-local.pth,其中包含/usr/local/lib/python2.7/site-packages/,然后系统python将添加该搜索路径。

To give a bit more explanation, Python will automatically construct its search paths (as mentioned above and here) using the site.py script (typically located in sys.prefix + lib/python<version>/site-packages as well as lib/site-python). One can obtain the value of sys.prefix:

python -c 'import sys; print(sys.prefix)'

The site.py script then adds a number of directories, dependent upon the platform, such as /usr/{lib,share}/python<version>/dist-packages, /usr/local/lib/python<version>/dist-packages to the search path and also searches these paths for <package>.pth config files which contain specific additional search paths. For example easy-install maintains its collection of installed packages which are added to a system specific file e.g on Ubuntu it’s /usr/local/lib/python2.7/dist-packages/easy-install.pth. On a typical system there are a bunch of these .pth files around which can explain some unexpected paths in sys.path:

python -c 'import sys; print(sys.path)'

So one can create a .pth file and put in any of these directories (including the sitedir as mentioned above). This seems to be the way most packages get added to the sys.path as opposed to using the PYTHONPATH.

Note: On OSX there’s a special additional search path added by site.py for ‘framework builds’ (but seems to work for normal command line use of python): /Library/Python/<version>/site-packages (e.g. for Python2.7: /Library/Python/2.7/site-packages/) which is where 3rd party packages are supposed to be installed (see the README in that dir). So one can add a path configuration file in there containing additional search paths e.g. create a file called /Library/Python/2.7/site-packages/pip-usr-local.pth which contains /usr/local/lib/python2.7/site-packages/ and then the system python will add that search path.


回答 7

对我来说,当我更改.bash_profile文件时它起作用了。只是更改.bashrc文件才有效,直到我重新启动外壳程序为止。

对于python 2.7,它应如下所示:

export PYTHONPATH="$PYTHONPATH:/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python"

.bash_profile文件末尾。

For me it worked when I changed the .bash_profile file. Just changing .bashrc file worked only till I restarted the shell.

For python 2.7 it should look like:

export PYTHONPATH="$PYTHONPATH:/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python"

at the end of the .bash_profile file.


回答 8

在Linux上,您可以创建从软件包到PYTHONPATH目录的符号链接,而不必处理环境变量。就像是:

ln -s /your/path /usr/lib/pymodules/python2.7/

On linux you can create a symbolic link from your package to a directory of the PYTHONPATH without having to deal with the environment variables. Something like:

ln -s /your/path /usr/lib/pymodules/python2.7/

回答 9

export PYTHONPATH="${PYTHONPATH}:/my/other/path"如果PYTHONPATH当前不存在,则添加到〜/ .bashrc可能不起作用(因为:)。

export PYTHONPATH="/my/other/path1"
export PYTHONPATH="${PYTHONPATH}:/my/other/path2"

将以上内容添加到我的〜/ .bashrc中可以在Ubuntu 16.04上为我实现窍门

Adding export PYTHONPATH="${PYTHONPATH}:/my/other/path" to the ~/.bashrc might not work if PYTHONPATH does not currently exist (because of the :).

export PYTHONPATH="/my/other/path1"
export PYTHONPATH="${PYTHONPATH}:/my/other/path2"

Adding the above to my ~/.bashrc did the trick for me on Ubuntu 16.04


回答 10

在MacOS上,而不是提供到特定库的路径。提供到根项目文件夹的完整路径

~/.bash_profile 

让我过得愉快,例如:

export PYTHONPATH="${PYTHONPATH}:/Users/<myuser>/project_root_folder_path"

在此之后:

source ~/.bash_profile

On MacOS, Instead of giving path to a specific library. Giving full path to the root project folder in

~/.bash_profile 

made my day, for example:

export PYTHONPATH="${PYTHONPATH}:/Users/<myuser>/project_root_folder_path"

after this do:

source ~/.bash_profile

回答 11

只是对awesomo的答案添加,也可以添加该行到您~/.bash_profile~/.profile

Just to add on awesomo’s answer, you can also add that line into your ~/.bash_profile or ~/.profile


回答 12

通过以下方式手动添加到PYTHONPATH的新路径:

在终端中通过以下方式将路径添加到〜/ .bashrc配置文件中:

vim ~/.bashrc

将以下内容粘贴到您的个人资料中

export PYTHONPATH="${PYTHONPATH}:/User/johndoe/pythonModule"

然后,确保在终端中运行代码时都获取bashrc配置文件的来源:

source ~/.bashrc 

希望这可以帮助。

The add a new path to PYTHONPATH is doing in manually by:

adding the path to your ~/.bashrc profile, in terminal by:

vim ~/.bashrc

paste the following to your profile

export PYTHONPATH="${PYTHONPATH}:/User/johndoe/pythonModule"

then, make sure to source your bashrc profile when ever you run your code in terminal:

source ~/.bashrc 

Hope this helps.


回答 13

我在Windows Vista中永久添加了Python 3.5

系统>控制面板>高级系统设置>高级(点击)环境变量>系统变量>(如果在“变量”列中没有看到PYTHONPATH)(单击)新建>变量名称:PYTHONPATH>变量值:

请在变量值中写入目录。这是Blue Peppers答案的细节。

I added permanently in Windows Vista, Python 3.5

System > Control Panel > Advanced system settings > Advanced (tap) Environment Variables > System variables > (if you don’t see PYTHONPATH in Variable column) (click) New > Variable name: PYTHONPATH > Variable value:

Please, write the directory in the Variable value. It is details of Blue Peppers’ answer.


回答 14

以下脚本是纯Python,因此可在所有平台上使用。它利用了https://docs.python.org/3/library/pathlib.html此处记录的pathlib路径,以使其跨平台工作。您只需运行一次,然后重新启动内核即可。受https://medium.com/@arnaud.bertrand/modifying-python-s-search-path-with-pth-files-2a41a4143574的启发。

from pathlib import Path
to_add=Path(path_of_directory_to_add)
from sys import path

if str(to_add) not in path:
    minLen=999999
    for index,directory in enumerate(path):
        if 'site-packages' in directory and len(directory)<=minLen:
            minLen=len(directory)
            stpi=index

    pathSitePckgs=Path(path[stpi])
    with open(str(pathSitePckgs/'current_machine_paths.pth'),'w') as pth_file:
        pth_file.write(str(to_add))

The script below works on all platforms as it’s pure Python. It makes use of the pathlib Path, documented here https://docs.python.org/3/library/pathlib.html, to make it work cross-platform. You run it once, restart the kernel and that’s it. Inspired by https://medium.com/@arnaud.bertrand/modifying-python-s-search-path-with-pth-files-2a41a4143574.

from pathlib import Path
to_add=Path(path_of_directory_to_add)
from sys import path

if str(to_add) not in path:
    minLen=999999
    for index,directory in enumerate(path):
        if 'site-packages' in directory and len(directory)<=minLen:
            minLen=len(directory)
            stpi=index

    pathSitePckgs=Path(path[stpi])
    with open(str(pathSitePckgs/'current_machine_paths.pth'),'w') as pth_file:
        pth_file.write(str(to_add))

回答 15

这是对此线程的更新,具有一些旧的答案。

对于使用MAC-OS Catalina或更高版本(> = 10.15)的用户,它引入了一个新的终端,名为zsh(替代旧的bash)。

由于此更改,上述答案有些问题,我通过创建文件~/.zshrc并将文件目录粘贴到$PATH和进行了一些变通方法$PYTHONPATH

所以,首先我做了:

nano ~/.zshrc

当编辑器打开时,我粘贴了以下内容:

export PATH="${PATH}:/Users/caio.hc.oliveira/Library/Python/3.7/bin"
export PYTHONPATH="${PYTHONPATH}:/Users/caio.hc.oliveira/Library/Python/3.7/bin"

保存它,然后重新启动终端。

重要提示:上面的路径设置为我计算机的路径,您必须将其调整为适合您的python。

This is an update to this thread which has some old answers.

For those using MAC-OS Catalina or some newer (>= 10.15), it was introduced a new Terminal named zsh (a substitute to the old bash).

I had some problems with the answers above due to this change, and I somewhat did a workaround by creating the file ~/.zshrc and pasting the file directory to the $PATH and $PYTHONPATH

So, first I did:

nano ~/.zshrc

When the editor opened I pasted the following content:

export PATH="${PATH}:/Users/caio.hc.oliveira/Library/Python/3.7/bin"
export PYTHONPATH="${PYTHONPATH}:/Users/caio.hc.oliveira/Library/Python/3.7/bin"

saved it, and restarted the terminal.

IMPORTANT: The path above is set to my computer’s path, you would have to adapt it to your python.


回答 16

在Python 3.6.4中,您可以像这样在python会话之间持久化sys.path:

import sys
import os

print(str(sys.path))

dir_path = os.path.dirname(os.path.realpath(__file__))
print(f"current working dir: {dir_path}")

root_dir = dir_path.replace("/util", '', 1)
print(f"root dir: {root_dir}")

sys.path.insert(0, root_dir)

print(str(sys.path))

我强烈建议您使用virtualenv和virtualenvwrapper,否则您的路径将会混乱

In Python 3.6.4 you can persist sys.path across python sessions like this:

import sys
import os

print(str(sys.path))

dir_path = os.path.dirname(os.path.realpath(__file__))
print(f"current working dir: {dir_path}")

root_dir = dir_path.replace("/util", '', 1)
print(f"root dir: {root_dir}")

sys.path.insert(0, root_dir)

print(str(sys.path))

I strongly suggest you use virtualenv and virtualenvwrapper otherwise you will clutter your path


回答 17

A <-> B之间的最短路径是一条直线;

import sys
if not 'NEW_PATH' in sys.path:
  sys.path += ['NEW_PATH']

Shortest path between A <-> B is a straight line;

import sys
if not 'NEW_PATH' in sys.path:
  sys.path += ['NEW_PATH']

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。