import os
print __file__
print os.path.dirname(__file__)
os.chdir('/tmp')
print __file__ # unchanged, of course
print os.path.dirname(__file__) # now broken
I have this issue above where dirname(__file__) can no longer be relied upon after os.chdir has been used in the script, after module loader has set __file__.
What is the usual mechanism for working around this, assuming you may not know where/when/how os.chdir may have been called previously?
edit: i hope this second example can better clarify my issue
import os
old_dir = os.getcwd()
print os.path.abspath(__file__)
os.chdir('/tmp')
print os.path.abspath(__file__)
os.chdir(old_dir)
the output is like this :
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
The
__file__must exist insys.pathsomewhere.