[Tutor] Converting code to string

Bernard Lebel 3dbernard at gmail.com
Thu Aug 23 23:14:41 CEST 2007


Hi Kent,

When try your approach, I get an IOError.

>>> import inspect
>>> def myFunc():
...     print 'hello world'
...
>>>
>>> s = inspect.getsource(myFunc)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "C:\Python24\lib\inspect.py", line 552, in getsource
    lines, lnum = getsourcelines(object)
  File "C:\Python24\lib\inspect.py", line 541, in getsourcelines
    lines, lnum = findsource(object)
  File "C:\Python24\lib\inspect.py", line 410, in findsource
    raise IOError('could not get source code')
IOError: could not get source code



Why? Because I'm using an API (the Softimage|XSI scripting API) where
I have to create a custom GUI (using that API's GUI toolkit).

I have to attach a logic callback to a number of widgets that can
change from one execution to the next.

The only way to do that, in that API, is to define the callback
functions "on-the-fly". And to define such a callback, the API
requires that the function must be represented as a string. All
strings are then joined and "injected" (the terminology used in the
doc) into the GUI object.

Since the XSI API also supports JScript, it is my feeling that this
part of the GUI toolkit was designed with JScript's toString() method
in mind, which works beautifully. I'm looking to do the same in
Python.


Thanks!
Bernard






On 8/23/07, Kent Johnson <kent37 at tds.net> wrote:
> Bernard Lebel wrote:
> > Hello,
> >
> > I'm looking for a way to convert Python code into a string.
> >
> > For example, let say I have this function:
> >
> > def myFunc():
> >     print 'hello world'
> >
> >
> > Now in the same module, I'd like to take this function and convert it
> > into a string:
> >
> > """def myFunc():
> >     print 'hello world'\n"""
>
> Try inspect.getsource(myFunc). But why?
>
> Kent
>


More information about the Tutor mailing list