如何永久添加Python导入路径?

cor*_*zza 10 python linux import

我知道我可以像这样添加Python的导入路径:

import sys

sys.path.append("/path/to/directory/")
Run Code Online (Sandbox Code Playgroud)

但是,当我重新启动Python时,这已经消失了.如果我不得不一直这样做,我会觉得很烦人,我想一劳永逸地做到这一点并完成它.

又怎样?我在哪里可以找到该文件?或者我是否需要编辑其他内容?我正在使用最新版本的Ubuntu.

tux*_*day 9

来自man python

   ~/.pythonrc.py
          User-specific initialization file loaded by the user module; not used by default or by most applications.

ENVIRONMENT VARIABLES

   PYTHONPATH
          Augments the default search path for module files.  The format is the same as the shell's $PATH: one or more directory  pathnames
          separated by colons.  Non-existent directories are silently ignored.  The default search path is installation dependent, but gen-
          erally begins with ${prefix}/lib/python<version> (see PYTHONHOME above).  The default search path is always appended to  $PYTHON-
          PATH.   If  a script argument is given, the directory containing the script is inserted in the path in front of $PYTHONPATH.  The
          search path can be manipulated from within a Python program as the variable sys.path .
Run Code Online (Sandbox Code Playgroud)


小智 5

您也可以使用路径文件。

如果要将名为 mymodule 的模块添加到导入路径,请将文件 mymodule.pth 添加到 3rd 方模块的标准目录中,通常称为 dist-packages 或 site-packages。在 Ubuntu 上,您可能会在类似的地方找到它

/usr/local/lib/python2.7/dist-packages
Run Code Online (Sandbox Code Playgroud)

文件 mymodule.pth 应包含一行,即您要添加到 python 导入路径的目录

<mymodule.pth>
/path/to/directory/containing/mymodule
Run Code Online (Sandbox Code Playgroud)

目录中的任何 python 模块或包现在都可以从解释器导入。