先来俩链接:
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
然后 , 看文章吧
<http://lucumr.pocoo.org/2011/2/1/exec-in-python/>
大概如下:
# -*- coding: utf-8 -*-
__author__ = 'lpe234'
x = """
import socket
def get_host():
return socket.gethostname()
"""
ns = dict()
exec x in ns
print ns['get_host']()