如何在 Python 3.1 中获取 exec() 的结果?
如何在Python 3.1中从exec()获取结果?
#!/usr/bin/python
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
host = socket.gethostname()
port = 1234
sock.bind((host,port))
ret_str = "executed"
while True:
cmd, addr = sock.recvfrom(1024)
if len(cmd) > 0:
print("Received ", cmd, " command from ", addr)
exec(cmd) # here I need execution results returns to ret_str
print( "results:", ret_str )
1 个回答
2
exec表达式不会返回值,建议使用eval函数。
print "result:", eval(cmd)
更新:如果你仍然需要这个,我在创建JSON-RPC的Python解释器时想出了这个小技巧 http://trypython.jcubic.pl
import sys
from StringIO import StringIO
__stdout = sys.stdout
sys.stdout = StringIO()
try:
#try if this is a expression
ret = eval(code)
result = sys.stdout.getvalue()
if ret:
result = result + ret
except:
try:
exec(code)
except:
#you can use <traceback> module here
result = 'Exception'
else:
result = sys.stdout.getvalue()
sys.stdout = __stdout