先來倆連接:python
http://stackoverflow.com/questions/701802/how-do-i-execute-a-string-containing-python-code-in-python
http://stackoverflow.com/questions/1015142/running-python-code-contained-in-a-string socket
而後 , 看文章吧spa
<http://lucumr.pocoo.org/2011/2/1/exec-in-python/>code
大概以下:utf-8
# -*- coding: utf-8 -*- __author__ = 'lpe234' x = """ import socket def get_host(): return socket.gethostname() """ ns = dict() exec x in ns print ns['get_host']()