在 Python 中向 sys.path 永久添加文件路径 [英] Permanently adding a file path to sys.path in Python

查看:123
本文介绍了在 Python 中向 sys.path 永久添加文件路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 example_file.py 的文件,我想从其他各种文件中使用它,所以我决定将 example_file.py 添加到 sys.path 并将此文件导入另一个文件以使用该文件.为此,我在 IPython 中运行了以下代码.

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

它工作得很好,但是一旦我从IPython出来,再次输入它并检查sys.path,我看到我添加的路径不存在,那怎么办我在 Python 中永久添加到 sys.path 的路径?

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?

推荐答案

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

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.

您也可以使用 PYTHONPATH 环境变量,它类似于系统 PATH 变量,但包含将添加到 sys.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.

请注意,无论您做什么,sys.path 都包含目录而不是文件.您不能将文件添加到 sys.path".你总是添加它的目录,然后你就可以导入文件了.

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.

这篇关于在 Python 中向 sys.path 永久添加文件路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆