[英]How to remove current directory from python import path
I want to work with the mercurial repository of hg
itself. 我想使用hg
本身的mercurial存储库。 That is, I cloned Mercurial from https://www.mercurial-scm.org/repo/hg and want to run some hg
commands inside the cloned repository. 也就是说,我从https://www.mercurial-scm.org/repo/hg克隆了Mercurial,并希望在克隆的存储库中运行一些hg
命令。 The problem is that when running hg
inside this clone hg
executable tries to load its python modules from this directory and not from /usr/lib/pythonVERSION
etc. As I understand it this happens because Python import path sys.path
contains an empty string as first entry which probably means "current directory". 问题是当在这个克隆中运行hg
时, hg
可执行文件试图从这个目录而不是从/usr/lib/pythonVERSION
等加载它的python模块。据我所知,这是因为Python导入路径sys.path
包含一个空字符串as第一个条目,可能意味着“当前目录”。 PYTHONPATH
environment variable is not set. 未设置PYTHONPATH
环境变量。
The questtion is how can I prevent my installed hg
from importing "wrong" modules. 问题是如何防止我安装的hg
导入“错误”模块。
The way I would deal with the topic is by creating a /usr/local/bin/hg
sh script with the following contents: 我处理这个主题的方法是创建一个/usr/local/bin/hg
sh脚本,其中包含以下内容:
#!/bin/sh
PYTHONPATH=/usr/lib/pythonVERSION/site-packages /usr/bin/hg
(Ubuntu-based distributives use dist-packages
instead of site-packages
) (基于Ubuntu的分发使用dist-packages
而不是site-packages
)
PYTHONPATH
is a special environment variable respected by Python interpreter to get extra module import paths. PYTHONPATH
是一个特殊的环境变量,受Python解释器的尊重,可以获得额外的模块导入路径。
Alternatively, you can export PYTHONPATH
into your shell, but it will affect your whole experience. 或者,您可以将PYTHONPATH
导出到shell中,但这会影响您的整体体验。
@ragol, i think Padraic has the correct solution. @ragol,我认为Padraic有正确的解决方案。 Within the python script that you are trying to run hg commands, you need to include the following command: sys.path.insert(0,"/usr/lib/pythonVERSION")
在您尝试运行hg命令的python脚本中,您需要包含以下命令: sys.path.insert(0,"/usr/lib/pythonVERSION")
Place the command at the very beginning of your python script. 将命令放在python脚本的最开头。 The command tells python to look in the /usr/lib/pythonVERSION
directory first when importing modules. 该命令告诉python在导入模块时首先查看/usr/lib/pythonVERSION
目录。
If that doesn't work, you may need to be more specific with the path. 如果这不起作用,您可能需要更具体的路径。 For example, if the module you are trying to import is located in the /usr/lib/pythonVERSION/site-packages/hg
directory, you could use the following command: sys.path.insert(0,"/usr/lib/pythonVERSION/site-packages/hg")
例如,如果您尝试导入的模块位于/usr/lib/pythonVERSION/site-packages/hg
目录中,则可以使用以下命令: sys.path.insert(0,"/usr/lib/pythonVERSION/site-packages/hg")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.