मैं जो अजगर 2.5 में ठीक चलाता है इस कोड लेकिन 2.7 में नहीं है:पायथन 2.7/exec/क्या गलत है?
import sys
import traceback
try:
from io import StringIO
except:
from StringIO import StringIO
def CaptureExec(stmt):
oldio = (sys.stdin, sys.stdout, sys.stderr)
sio = StringIO()
sys.stdout = sys.stderr = sio
try:
exec(stmt, globals(), globals())
out = sio.getvalue()
except Exception, e:
out = str(e) + "\n" + traceback.format_exc()
sys.stdin, sys.stdout, sys.stderr = oldio
return out
print "%s" % CaptureExec("""
import random
print "hello world"
""")
और मैं मिलता है:
string argument expected, got 'str' Traceback (most recent call last): File "D:\3.py", line 13, in CaptureExec exec(stmt, globals(), globals()) File "", line 3, in TypeError: string argument expected, got 'str'
माइनर टिप्पणियों की तरह कुछ लिखने की ज़रूरत: pythonic शैली केवल कक्षाओं के लिए TitleCase उपयोग करने के लिए है, यह होना चाहिए 'captureExec' या' capture_exec'। साथ ही, आपको विशेष रूप से 'प्रयास' में 'आयात करें' को पकड़ना चाहिए ... ब्लॉक को छोड़कर। 'बाइट्सियो' के लिए – katrielalex