Why does linecache avoid <stdin>? How can I get equivalent of inspect.getsource() for an interactive session?
Mark Hirota
markhirota at gmail.com
Thu Sep 9 16:22:39 EDT 2010
Here's my goal:
To enable a function for interactive session use that, when invoked,
will "put" source code for a specified object into a plaintext file.
Based on some initial research, this seems similar to ipython's %save
magic command (?)
Example:
def put(filename, object):
f = open(filename, "w")
f.write(inspect.getsource(object))
f.close()
Of course, in an interactive session, if you define a function:
>>> def addit(a,b): return a+b
And then try to run inspect.getsource() on it, you'll get an exception:
>>> inspect.getsource(addit)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python26\lib\inspect.py", line 689, in getsource
lines, lnum = getsourcelines(object)
File "C:\Python26\lib\inspect.py", line 678, in getsourcelines
lines, lnum = findsource(object)
File "C:\Python26\lib\inspect.py", line 526, in findsource
raise IOError('could not get source code')
IOError: could not get source code
This appears to be due to the fact that the linecache standard library
module doesn't include <stdin> (?)
Can anyone help shed some light on why this is -- and perhaps provide
feedback on whether this goal is feasible?
Thanks!
More information about the Python-list
mailing list