Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
393 views
in Technique[技术] by (71.8m points)

python - capturing dis.dis results

Is there any way to get the output of dis.dis() without redirecting sys.stdout? I have tried:

out=str(dis.dis())

and

out=""""""
out+=str(dis.dis())

However I soon found out that it returns None. Is there any way to fix this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Unfortunately, in Python versions before 3.4 the dis module uses print statements to stdout, so it won't return anything directly useful. Either you have to re-implement the dis, disassemble and disassemble_string functions, or you temporarily replace sys.stdout with an alternative to capture the output:

import sys
from cStringIO import StringIO

out = StringIO()
stdout = sys.stdout
sys.stdout = out
try:
    dis.dis()
finally:
    sys.stdout = stdout
out = out.getvalue()

This is actually best done using a context manager:

import sys
from contextlib import contextmanager
from cStringIO import StringIO

@contextmanager
def captureStdOut(output):
    stdout = sys.stdout
    sys.stdout = output
    try:
        yield
    finally:
        sys.stdout = stdout

out = StringIO()
with captureStdOut(out):
    dis.dis()
print out.getvalue()

That way you are guaranteed to have stdout restored even if something goes wrong with dis. A little demonstration:

>>> out = StringIO()
>>> with captureStdOut(out):
...     dis.dis(captureStdOut)
... 
>>> print out.getvalue()
 83           0 LOAD_GLOBAL              0 (GeneratorContextManager)
              3 LOAD_DEREF               0 (func)
              6 LOAD_FAST                0 (args)
              9 LOAD_FAST                1 (kwds)
             12 CALL_FUNCTION_VAR_KW     0
             15 CALL_FUNCTION            1
             18 RETURN_VALUE        

In Python 3.4 and up, the relevant functions take a file parameter to redirect output to:

from io import StringIO

with StringIO() as out:
    dis.dis(file=out)
    print(out.getvalue())

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...