[Tutor] Converting code to string

Eric Brunson brunson at brunson.com
Thu Aug 23 23:50:59 CEST 2007


Bernard Lebel wrote:
> 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
>   

My guess is that's because you're doing it interactively.  Try putting 
that in a file and it should work.

>
>
> 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.
>   

Then why not just define them as text strings?  Then you can inject 
them, or if you need to execute them outside of the API, you can still 
compile and run them.

If that's not a good idea, them my next thought would be to put all 
these callbacks in a single file.  You then have the options of 
importing the functions from the file (module), or to parse the file 
assigning the functions to a dictionary indexed by the name of the 
function. 

You make it seem like it wasn't your choice to use this API, but without 
knowing more about it, it sounds incredibly lame.

> 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
>>
>>     
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>   



More information about the Tutor mailing list