天天看點

從例子看python __file__

# -*- coding: utf-8 -*-
from termcolor import colored
import sys
print(colored('sys.path=','cyan'))
print(sys.path)

import os
print()

print(colored('__file__=','cyan'))
print(__file__)

print()
print(colored('os.path.dirname(__file__)=','cyan'))
print(os.path.dirname(__file__))

print()
print(colored('os.path.realpath(__file__)=','cyan'))
print(os.path.realpath(__file__))

print()
print(colored("os.paht.join(os.path.dirname(__file__),'..'=",'cyan'))
print(os.path.join(os.path.dirname(__file__), '..'))

print()
print(colored('os.path.dirname(os.path.realpath(__file__)=','cyan'))
print(os.path.dirname(os.path.realpath(__file__)))

print()
print(colored('os.path.abspath(os.path.dirname(__file__)=','cyan'))
print(os.path.abspath(os.path.dirname(__file__)))      

直接在spyder IDE中按運作鍵運作

輸出:

從例子看python __file__
sys.path=
['/usr/lib/python36.zip', '/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload', '', '/home/dell/workenv/lib/python3.6/site-packages', '/home/dell/myprojects/pybullet/src/rllib/gym-pybullet', '/home/dell/workenv/lib/python3.6/site-packages/IPython/extensions', '/home/dell/myprojects/pybullet/src/rllib', '/home/dell/.ipython']

__file__=
/home/dell/myprojects/pybullet/src/rllib/test_file.py

os.path.dirname(__file__)=
/home/dell/myprojects/pybullet/src/rllib

os.path.realpath(__file__)=
/home/dell/myprojects/pybullet/src/rllib/test_file.py

os.paht.join(os.path.dirname(__file__),'..'=
/home/dell/myprojects/pybullet/src/rllib/..

os.path.dirname(os.path.realpath(__file__)=
/home/dell/myprojects/pybullet/src/rllib

os.path.abspath(os.path.dirname(__file__)=
/home/dell/myprojects/pybullet/src/rllib      

分析:

  1. 我目前的解釋器是virtualenv環境下的python3.6,而這個解釋器在sys.path路徑中
  2. file輸出的就是這個python檔案自己的路徑
  3. dirname輸出的是python檔案所在的檔案夾名稱
  4. realpath就是檔案的絕對路徑,和file是相同的

而我們看下一種情況,同樣的代碼輸出會有所不同

在終端中通過 python test_file.py執行

輸出:

sys.path=
['/home/dell/myprojects/pybullet/src/rllib', '/usr/lib/python36.zip', '/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload', '/home/dell/workenv/lib/python3.6/site-packages', '/home/dell/myprojects/pybullet/src/rllib/gym-pybullet']

__file__=
test_file.py

os.path.dirname(__file__)=


os.path.realpath(__file__)=
/home/dell/myprojects/pybullet/src/rllib/test_file.py

os.paht.join(os.path.dirname(__file__),'..'=
..

os.path.dirname(os.path.realpath(__file__)=
/home/dell/myprojects/pybullet/src/rllib

os.path.abspath(os.path.dirname(__file__)=
/home/dell/myprojects/pybullet/src/rllib      
  1. file就隻顯示自己的檔案名稱
  2. dirname(file)不顯示任何東西
  3. join顯示的是相對路徑
  4. 是以,這樣執行方式輸出的都是相對路徑
  5. 因為目前解釋器在sys.path中,是以才以相對路徑的方式工作
  6. 至于為什麼在IDE中是以絕對路徑的方式,我也不知道,誰能告訴我一下

再來看一個例子

import os, inspect
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(os.path.dirname(currentdir))
os.sys.path.insert(0, parentdir)