python – __file__和os.path模块不能很好地播放?

import os
print __file__
print os.path.dirname(__file__)
os.chdir('/tmp')
print __file__  # unchanged, of course
print os.path.dirname(__file__)  # now broken

我有上面的这个问题,在模块加载器设置了__file__之后,在脚本中使用了os.chdir后,再也不能依赖dirname(__ file__)了.

解决这个问题的常用机制是什么,假设您可能不知道之前/何时/如何调用os.chdir?

编辑:我希望第二个例子可以更好地澄清我的问题

import os
old_dir = os.getcwd()
print os.path.abspath(__file__)
os.chdir('/tmp')
print os.path.abspath(__file__)
os.chdir(old_dir)

输出是这样的:

wim@wim-acer:~$python --version
Python 2.7.1+
wim@wim-acer:~$pwd
/home/wim
wim@wim-acer:~$python /home/wim/spam.py
/home/wim/spam.py
/home/wim/spam.py
wim@wim-acer:~$python ./spam.py
/home/wim/spam.py
/tmp/spam.py

最佳答案 __file__必须存在于某个地方的sys.path中.

for dirname in sys.path:
   if os.path.exists( os.path.join(dirname,__file__) ):
       # The directory name for `__file__` was dirname
点赞