Ubuntu添加目录到Python路径

14

我想在我的Ubuntu电脑上运行用Python编写的第三方工具(corgy工具)。

然而,我不知道如何将额外的模块添加到Python路径中。

cat doc/download.rst         
There is currently no setup.py, so you need to manually add
the download directory to your PYTHON_PATH environment variable.

如何将目录添加到PYTHON_PATH中?

我已尝试过:
export PYTHON_PATH=/home/user/directory:$PYTHON_PATH && source .bashrc
export PATH=/home/user/directory:$PATH && source .bashrc

python
import sys
sys.path.append("/home/user/directory/")

但是当我尝试运行这个工具时,我遇到了问题:

Traceback (most recent call last):
File "examples/dotbracket_to_bulge_graph.py", line 4, in <module>
import corgy.graph.bulge_graph as cgb
ImportError: No module named corgy.graph.bulge_graph
2个回答

14
在你的主目录下创建一个名为.bash_profile的文件。然后,添加这一行:
PYTHONPATH=$PYTHONPATH:new_dir
EXPORT $PYTHONPATH

甚至更好的是:

if [ -d "new_dir" ] ; then
  PYTHONPATH="$PYTHONPATH:new_dir"
fi
EXPORT $PYTHONPATH

.bash_profile文件中的属性在每次登录时都会加载。

source命令非常有用,如果你不想再次登录。


你能解释一下这与导出调用有什么不同吗? - njzk2
@njzk2 export 只是为当前会话设置变量。这也可以工作,但只有在您退出之前有效。当然,source .bashrc 是没有意义的。 - kirelagin
1
而且,更重要的是,在.bash_profile中设置变量时,您必须使用“export”。 - kirelagin
在https://dev59.com/PHRC5IYBdhLWcg3wFNDX中有一个很好的解释。我不知道在bash_profile中需要`EXPORT`。我相应地更新了我的答案。 - fedorqui
这是我的观点。如果简单的导出不起作用,我不认为将其添加到bash_profile有什么帮助,除非脚本生成了一个新会话。 - njzk2

5

@fedorqui上面的答案对我来说几乎是好的,但至少有一个错误(我不确定export语句中的大写字母是否正确,我是一个完全的新手)。 在导出语句中,PYTHONPATH前面不应该有$符号。因此,选项将是:

Create a .bash_profile in your home directory. Then, add the line

PYTHONPATH=$PYTHONPATH:new_dir
export PYTHONPATH

Or even better:

if [ -d "new_dir" ] ; then
  PYTHONPATH="$PYTHONPATH:new_dir"
fi
export PYTHONPATH

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接