[Python-au] output of dis.dis(lambda x: x)

Andrew McNamara andrewm at object-craft.com.au
Thu Apr 19 00:40:08 UTC 2007

>for disassembling some python code i use the dis-function of the
>dis-module. i need the result as a python string, but the dis-function
>only sends the output to stdout.

Looking at the source confirms this (it uses the print keyword). BTW,
don't be afraid to look at the python source (modules, or the python
core itself).

>as a workaround i tried this:
>import dis, cStringIO, sys
>old_stdout = sys.stdout
>out = cStringIO.StringIO()
>sys.stdout = out
>dis.dis(lambda x: x)
>sys.stdout = old_stdout
>after that i get the disassembled result by using out.getvalue()
>until now it works for me, but its not a nice way, because i already
>redirect the sys.stdout in my application to a log-window, thats why i
>have to save the previously value of sys.stdout in old_stdout.
>Does anyone has a better solution??

Not really - I'd just suggest wrapping it in a function and using a
try/finally block like this:

    def dis_str(code):
        out = cStringIO.StringIO()
        old_stdout = sys.stdout
            sys.stdout = out
            sys.stdout = old_stdout
        return out.getvalue()

Andrew McNamara, Senior Developer, Object Craft

More information about the python-au mailing list