Why does linecache avoid <stdin>? How can I get equivalent of inspect.getsource() for an interactive session?

Thomas Jollans thomas at jollybox.de
Fri Sep 10 00:19:51 CEST 2010

On Thursday 09 September 2010, it occurred to Mark Hirota to exclaim:
> 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)

What inspect.getsource is is simply this: It finds out which module the object 
belongs to, checks the __file__ of that module, opens it (or the corresponsing 
.py file), and finds the right bit. This won't work for extension modules as 
they have no Python source, and it won't work for objects created on the 
interactive console or using exec, or eval, as they have no source file.

> 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