将目录添加到sys.path/PYTHONPATH [英] adding directory to sys.path /PYTHONPATH

查看:360
本文介绍了将目录添加到sys.path/PYTHONPATH的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从特定目录导入模块.

I am trying to import a module from a particular directory.

问题是,如果我使用sys.path.append(mod_directory)附加路径,然后打开python解释器,则目录mod_directory将添加到列表sys.path的末尾.如果在打开python解释器之前导出PYTHONPATH变量,该目录将添加到列表的开头.在后一种情况下,我可以导入模块,但是在前一种情况下,我不能.

The problem is that if I use sys.path.append(mod_directory) to append the path and then open the python interpreter, the directory mod_directory gets added to the end of the list sys.path. If I export the PYTHONPATH variable before opening the python interpreter, the directory gets added to the start of the list. In the latter case I can import the module but in the former, I cannot.

有人可以解释为什么会这样吗,请给我一个将mod_directory添加到开始 inside python脚本的解决方案吗?

Can somebody explain why this is happening and give me a solution to add the mod_directory to the start, inside a python script ?

推荐答案

这已在文档中说明. PYTHONPATH中指定的任何路径通常都记录在工作目录之后,但在标准解释器提供的路径之前. sys.path.append()追加到现有路径.请参见此处

This is working as documented. Any paths specified in PYTHONPATH are documented as normally coming after the working directory but before the standard interpreter-supplied paths. sys.path.append() appends to the existing path. See here and here. If you want a particular directory to come first, simply insert it at the head of sys.path:

import sys
sys.path.insert(0,'/path/to/mod_directory')

也就是说,与使用PYTHONPATH或直接操作sys.path相比,通常有更好的方法来管理导入.例如,请参见此问题的答案.

That said, there are usually better ways to manage imports than either using PYTHONPATH or manipulating sys.path directly. See, for example, the answers to this question.

这篇关于将目录添加到sys.path/PYTHONPATH的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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