在Python中将文件路径永久添加到sys.path

问题:在Python中将文件路径永久添加到sys.path

我有一个名为的文件example_file.py,我想从其他文件中使用它,因此我决定将其添加example_file.pysys.path另一个文件中并将其导入另一个文件中以使用该文件。为此,我在IPython中运行了以下内容。

import sys
sys.path
sys.path.append('/path/to/the/example_file.py')
print(sys.path)

我可以看到我刚刚添加的路径,并且当我尝试从另一个目录路径中导入该文件时,如下所示:

import example_file

它工作正常,但是一旦我退出IPython,再次输入它,并检查了sys.path,我发现添加的路径不存在,那么如何在Python中永久地向sys.path添加路径?

I had a file called example_file.py, which I wanted to use from various other files, so I decided to add example_file.py to sys.path and import this file in another file to use the file. To do so, I ran the following in IPython.

import sys
sys.path
sys.path.append('/path/to/the/example_file.py')
print(sys.path)

I could see the path I had just added, and when I tried to import this file from another directory path like this:

import example_file

it worked just fine, but once I came out of IPython, entered it again, and checked the sys.path, I saw that the path which I had added was not present, so how do I add a path to sys.path permanently in Python?


回答 0

有几种方法。其中一个最简单的就是创建一个my-paths.pth文件(如描述在这里)。这只是具有.pth您在系统site-packages目录中放入的扩展名的文件。在文件的每一行上都放置一个目录名,因此您可以在其中放置一行/path/to/the/,它将目录添加到路径中。

您还可以使用PYTHONPATH环境变量,该变量类似于系统PATH变量,但包含将添加到的目录sys.path。请参阅文档

请注意,无论您做什么,都sys.path包含目录而不是文件。您不能“将文件添加到sys.path”。您始终添加其目录,然后可以导入文件。

There are a few ways. One of the simplest is to create a my-paths.pth file (as described here). This is just a file with the extension .pth that you put into your system site-packages directory. On each line of the file you put one directory name, so you can put a line in there with /path/to/the/ and it will add that directory to the path.

You could also use the PYTHONPATH environment variable, which is like the system PATH variable but contains directories that will be added to sys.path. See the documentation.

Note that no matter what you do, sys.path contains directories not files. You can’t “add a file to sys.path“. You always add its directory and then you can import the file.


回答 1

这种方式为我工作:

添加您喜欢的路径:

export PYTHONPATH=$PYTHONPATH:/path/you/want/to/add

检查:您可以运行’export’cmd并检查输出,也可以使用以下cmd进行检查:

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

This way worked for me:

adding the path that you like:

export PYTHONPATH=$PYTHONPATH:/path/you/want/to/add

checking: you can run ‘export’ cmd and check the output or you can check it using this cmd:

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