求Mac下Python路径的手动设置方法?

援引文档[1]:

When a module named spam is imported, the interpreter first searches for a built-in module with that name. If not found, it then searches for a file named spam.py in a list of directories given by the variable sys.path. sys.path is initialized from these locations:

  • the directory containing the input script (or the current directory).
  • PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH).
  • the installation-dependent default.
After initialization, Python programs can modify sys.path. The directory containing the script being run is placed at the beginning of the search path, ahead of the standard library path. [...]

假设你在 ~/code/django/mysite 下面执行 python manage.py shell,然后在其中执行

import sys; print sys.path

你会得到一个以 ~/code/django/mysite 为第〇个元素的 list,而如果不通过 manage.py 直接运行 python 之后再执行同样的命令,会发现 sys.path 的第〇元素只是空字符串。为什么呢?再次援引文档[2]:

A list of strings that specifies the search path for modules. Initialized from the environment variable PYTHONPATH, plus an installation-dependent default.

As initialized upon program startup, the first item of this list, path[0], is the directory containing the script that was used to invoke the Python interpreter. If the script directory is not available (e.g. if the interpreter is invoked interactively or if the script is read from standard input), path[0] is the empty string, which directs Python to search modules in the current directory first. Notice that the script directory is inserted before the entries inserted as a result of PYTHONPATH.

A program is free to modify this list for its own purposes.

事实上也有很多程序会去改变 sys.path[3]。不过,只要你从 ~/code/django/mysite 下面调用 python shell,就可以 import polls,因为 polls 是当前目录下面的子目录。

如此一来 IDLE 的问题就很清楚了。虽然很久没有用过 IDLE 不太记得里面的 sys.path 是怎样的,但我想你启动它时它的「当前目录」并不是 ~/code/django/mysite,PYTHONPATH 也并未被设定好。解决方法有三个(均未经验证):
  1. 进入 ~/code/django/mysite 之后在命令行下输入 idle 回车,而不是用鼠标去 Application 里点 IDLE。这样一来 IDLE 启动之后的 module 搜索路径就包含当前目录下面的 polls 子目录。
  2. 在调用 IDLE 之前设定 PYTHONPATH 环境变量。设定它又有三种方法,均未经验证:
    1. 任意命令行下运行
      PYTHONPATH=/foo/bar idle
      注意这是一行命令。这适用于只需要一次性设定PYTHONPATH的场合,当 idle 结束返回之后,PYTHONPATH也就失效了,不会影响其他程序。
    2. 在你的 .bash_profile 或者 .zshrc 里面设定 PYTHONPATH,比如
      export PYTHONPATH=/foo/bar
      这样一来所有从命令行下面启动的 Python 程序都会看到它。
    3. 利用 /etc/launchd.conf 设定环境变量,这样一来所系统有 Python 程序,无论是否从命令行下启动,都会看到它。
  3. 运行 IDLE 后,手动更改 sys.path,例如
    import sys; sys.path.append('/foo/bar')
但其实上述三个方法都太不爽了。其实……你为什么要用 IDLE 这个鸡肋的东西?我给你介绍一位新朋友:iPython 。它强大在哪里,你看一遍它的网站就知道了。

而且更强大的是,只要你 pip install ipython,再去 python manage.py shell 的时候,Django 就会自动调用 iPython 作为 shell。

[1] docs.python.org/2/tutor
[2] docs.python.org/2/libra
[3] github.com/django/djang 第 43 行
原发布于 https://www.zhihu.com/question/21592894/answer/18733125