exec在python脚本中不起作用

时间:2016-03-14 08:09:06

标签: python

我在python中有一个套接字服务器程序,它从各种客户端获取数据并执行它并返回输出。下面给出的是服务器代码,exec语句不会抛出任何错误,但是不会创建输出图像。在python命令行界面中运行时,确切的代码工作正常。输出图像已保存。

#!/usr/bin/python           # This is server.py file

import socket               # Import socket module

s = socket.socket()         # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345                # Reserve a port for your service.
s.bind((host, port))        # Bind to the port

s.listen(5)                 # Now wait for client connection.
tmp_str = "'''"
message = ""
saveImage = "pl.savefig('mytest.png',   bbox_inches='tight')"
while True:
   c, addr = s.accept()     # Establish connection with client.
   print 'Got connection from', addr
   reply = c.recv(4096)
   print 'Raw socket message = ', reply

   tmpstr = "'''" + reply + saveImage + "'''"
   print 'executed statement = ', tmpstr

   exec(tmpstr)
   print 'Sending message', host
   c.sendall(host)
   reply = c.recv(4096)
   print 'script contains', reply
   c.close()                # Close the connection

输出

Got connection from ('xxx.xxx.xxx.17', 53403)
Raw socket message =  import pylab as pl
import numpy as np
y = pl.randn(100)
pl.plot(y)

executed statement =  '''import pylab as pl
import numpy as np
y = pl.randn(100)
pl.plot(y)
pl.savefig('mytest.png', bbox_inches='tight')'''
Sending message MacBook-Pro-3.local
script contains Hello from /xxx.xxx.xxx.17:53403

我不确定exec是否实际执行过内部的语句。 Savefig不会创建mytest.png文件,而从python环境执行时它可以正常工作。

命令行输出

>>> statement =  '''import pylab as pl
... import numpy as np
... y = pl.randn(100)
... pl.plot(y)
... pl.savefig('mytest.png', bbox_inches='tight')'''
>>> exec(statement)
>>> 

这里的任何帮助都会很棒。

0 个答案:

没有答案