如何从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 )
答案 0 :(得分:2)
exec表达式不会返回值使用eval函数。
print "result:", eval(cmd)
更新:如果您仍然需要这个,我在创建JSON-RPC python解释器http://trypython.jcubic.pl
时想出了这个hackimport 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