次のようにPythonにインポートパスを追加できることを知っています。
import sys
sys.path.append("/path/to/directory/")
しかし、Pythonを再起動すると、これはなくなります。これをずっとやらなければならないのはかなり面倒だと思います。これを一度だけやり、それでやりたいと思っています。
それで、どうやって?そのファイルはどこにありますか?または、何か他のものを編集する必要がありますか?最新バージョンのUbuntuを使用しています。
manpythonから
~/.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 .
パスファイルを使用することもできます。
mymoduleというモジュールをインポートパスに追加する場合は、ファイルmymodule.pthをサードパーティモジュールの標準ディレクトリ(通常はdist-packagesまたはsite-packagesと呼ばれます)に追加します。Ubuntuではおそらく次のような場所にあります
/usr/local/lib/python2.7/dist-packages
ファイルmymodule.pthには、Pythonインポートパスに追加するディレクトリである1行が含まれている必要があります。
<mymodule.pth>
/path/to/directory/containing/mymodule
これで、ディレクトリ内のすべてのPythonモジュールまたはパッケージがインタプリタからインポート可能になります。
シェルから次を実行します。
echo -e "\nexport PYTHONPATH=\$PYTHONPATH:/path/to/directory" >> ~/.bashrc
再起動します
PYTHONPATHディレクトリを含めるために呼び出される環境変数を設定できます。
ドキュメントでそれについてもっと読む