从例子看python __file__
原创
©著作权归作者所有:来自51CTO博客作者bug404的原创作品,请联系作者获取转载授权,否则将追究法律责任
# -*- 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中按运行键运行
输出:
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
分析:
- 我当前的解释器是virtualenv环境下的python3.6,而这个解释器在sys.path路径中
- file输出的就是这个python文件自己的路径
- dirname输出的是python文件所在的文件夹名称
- 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
情况就有所不同
分析:
- file就只显示自己的文件名称
- dirname(file)不显示任何东西
- join显示的是相对路径
- 所以,这样执行方式输出的都是相对路径
- 因为当前解释器在sys.path中,所以才以相对路径的方式工作
- 至于为什么在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)