1python
C:test [dir] getpath [file] path.py [dir] sub [file] sub_path.py
好比shell
C:\test目录下还有一个名为sub的目录;spa
C:\test目录下有getpath.py,sub目录下有 sub_path.py,getpath.py调用sub_path.py;code
咱们在C:\test下执行getpath.py。若是咱们在 sub_path.py里面使用sys.path[0],那么其实获得的是getpath.py所在的目录路径“C:\test”,由于Python虚拟 机是从getpath.py开始执行的。若是想获得sub_path.py的路径,那么得这样:
os.path.split(os.path.realpath(__file__))[0]get
验证:it
而后咱们在C:\test下面执行python getpath/path.py,这时sub_path.py里面与各类用法对应的值实际上是:
os.getcwd() “C:\test”,取的是起始执行目录
sys.path[0]或sys.argv[0] “C:\test\getpath”,取的是被初始执行的脚本的所在目录
os.path.split(os.path.realpath(__file__))[0] “C:\test\getpath\sub”,取的是__file__所在文件sub_path.py的所在目录class