How to remove current directory from python import path

浪尽此生 提交于 2019-12-12 09:36:00

问题


I want to work with the mercurial repository of hg itself. That is, I cloned Mercurial from https://www.mercurial-scm.org/repo/hg and want to run some hg commands inside the cloned repository. 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". PYTHONPATH environment variable is not set.

The questtion is how can I prevent my installed hg from importing "wrong" modules.


回答1:


The way I would deal with the topic is by creating a /usr/local/bin/hg sh script with the following contents:

#!/bin/sh
PYTHONPATH=/usr/lib/pythonVERSION/site-packages /usr/bin/hg

(Ubuntu-based distributives use dist-packages instead of site-packages)

PYTHONPATH is a special environment variable respected by Python interpreter to get extra module import paths.

Alternatively, you can export PYTHONPATH into your shell, but it will affect your whole experience.




回答2:


@ragol, i think Padraic has the correct solution. 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")

Place the command at the very beginning of your python script. The command tells python to look in the /usr/lib/pythonVERSION directory first when importing modules.

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")



来源:https://stackoverflow.com/questions/25533631/how-to-remove-current-directory-from-python-import-path

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!