每当我使用sys.path。追加,新目录将被添加。然而,一旦我关闭python,列表将恢复到以前的(默认?)值。如何将目录永久添加到PYTHONPATH?


当前回答

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

~/.bash_profile 

让我很开心,例如:

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

这样做之后:

source ~/.bash_profile

其他回答

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

~/.bash_profile 

让我很开心,例如:

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

这样做之后:

source ~/.bash_profile

除了操作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"

向PYTHONPATH添加新路径是手动执行的:

将路径添加到~/。Bashrc剖面,在终端由:

vim ~/.bashrc

将以下内容粘贴到您的配置文件中

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

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

source ~/.bashrc 

希望这能有所帮助。

受到andrei-deusteanu答案的启发,以下是我的版本。这允许您在site-packages目录中创建许多额外的路径。

import os

# Add paths here.  Then Run this block of code once and restart kernel. Paths should now be set.
paths_of_directories_to_add = [r'C:\GIT\project1', r'C:\GIT\project2', r'C:\GIT\project3']

# Find your site-packages directory
pathSitePckgs = os.path.join(os.path.dirname(os.__file__), 'site-packages')

# Write a .pth file in your site-packages directory
pthFile = os.path.join(pathSitePckgs,'current_machine_paths.pth')
with open(pthFile,'w') as pth_file:
    pth_file.write('\n'.join(paths_of_directories_to_add))

print(pthFile)

我找到了一个解决方案,在水蟒环境中做到这一点:https://datacomy.com/python/anaconda/add_folder_to_path/

只是:

Conda develop /your_path