__file__ and os.path module not playing well?

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 question above where dirname(__file__) can no longer be relied upon after os.chdir was used in the script, after the module loader installed __file__ .

What is the usual mechanism for working on this if you do not know where / when / how os.chdir could have been called before?

edit: I hope this second example can better clarify my problem

 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 as follows:

 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 
+4
source share
2 answers

__file__ must exist somewhere in sys.path .

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

In the last example, there is a relative path element in the name __file__ ( ./xxx.py ). When abspath is invoked so that it expands to the current directory.

If you put this code in a module, you will not have this problem.

+1
source

All Articles