Pulpcode

捕获,搅碎,拼接,吞咽

0%

python的那些路径

当前路径(执行一段脚本)test.py

1
2
print "nihao,neng bu neng jie wo liang kuai qian"
# 下次你看见一个外国人,可以这样说。

你可以这样执行:

$ python test.py

如果你不用python, shell是不会知道如何解决这段脚本的。
除非你在这个脚本的第一行加上一句话(写过shell脚本的都知道)

#!/usr/bin/python

这样shell就知道如何运行你的脚本了
但是你如果直接test.py,它还是无法找到,因为shell查找程序的路径并不包含当前路径
除非你这样./test.py 运行,我们写c程序的时候,也要./a.out这样运行。
或者把当前路径添加进来,那么就可以直接运行了。

那么这么方便的东西,linux为什么自己不做呢?因为这样很不安全,想想,有人在你的文件夹里,写了一个脚本,递归rm,然后命名为ls,你在这个目录下一个ls命名…..世界都清静了…

解释器的目录

python解释器会在哪里找模块?
这个问题的起因是c语言嵌入python中,python解释器并能找到当前目录下的模块,这跟我们认为的常理并不同,因为如果我在一个目录写下一个脚本test.py,比如

1
2
def hello():
print "nihao"

那么我在当前目录下运行python解释器,它是可以找到这个脚本的。

>>> import test
>>> test.hello()
>>> nihao

但是为什么在c嵌入python后就不行了呢?
为了解决这个问题,我先试着在普通的python解释器,和c嵌入的解释器,运行这些语句:

1
2
import sys, pprint
pprint.pprint(sys.path)

众所周知,sys.path包含一个字符串组成的目录列表,解释器就在该列表中查找模块.
我发现,这两个打印出来的path,有不同之初,普通解释器多了一个’’,一个空的字符串,这难道就是当前目录?

当我试着在sys.path删除这个空字符串的时候,它还真的不能导入当前目录的模块,
看来这两者初始化解释器的方式并不同,当然,我还是没有证据,证明。
对于我这种有强迫症的人,当然忍不住,最后,一个大神在python邮件列表里告诉了我。

python文档有关介绍:

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.

这个故事告诉我们,学好英语很重要,大神都是直接看官方文档的….