Issue 15931: inspect.findsource fails after directory change (original) (raw)
The attached script works in 2.6(.4) but not in 2.7(.3); the script cannot locate its own source code if invoked by relative path and work directory has changed. If line 8 uncommented, everything is fine due to caching.
I think this is related to issue #4050 changes in inspect.py.
~ kgabor$ python ./instest.py
None ./instest.py Traceback (most recent call last): File "./instest.py", line 10, in print inspect.getsourcefile(A), inspect.getfile(A),inspect.findsource(A) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/inspect.py", line 529, in findsource raise IOError('source code not available') IOError: source code not available
~ kgabor$ pwd /Users/kgabor
~ kgabor$ python /Users/kgabor/instest.py
/Users/kgabor/instest.py /Users/kgabor/instest.py (['import inspect\n', 'import os\n', '\n', 'class A:\n', ' def init(self):\n', ' self.a=1\n', '\n', '#print inspect.getsourcefile(A),inspect.getfile(A),inspect.findsource(A)\n', "os.chdir('/')\n", 'print inspect.getsourcefile(A), inspect.getfile(A),inspect.findsource(A)\n'], 3)
Hm, maybe just for the imports? This simple script, run it directly:
test.py:
def foo(): pass print(foo.code.co_filename)
"$ python3.4 test.py" will still print relative path "test.py".
Hence, if you do 'os.chdir' in the above script, the introspection code will break. There are many similar issues on the tracker, btw.