python提高--running-python-code-contained-in-a-strin

时间:2022-07-22
本文章向大家介绍python提高--running-python-code-contained-in-a-strin,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

先来俩链接:

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

然后 , 看文章吧

Be careful with exec and eval in Python

<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']()