Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/three.js/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python从字符串导入代码_Python_Google App Engine - Fatal编程技术网

python从字符串导入代码

python从字符串导入代码,python,google-app-engine,Python,Google App Engine,我使用的是谷歌应用引擎,我试图基本上允许用户上传代码,稍后由服务器执行。我还必须能够将变量发送到脚本,这就是为什么最初在我运行桌面上的所有内容时,我会动态地导入所有内容(例如,脚本的名称存储在变量中)。但现在我不能这样做,因为谷歌应用程序引擎环境中有文件系统 我已经有一个数据库设置,这样我可以得到纯文本的代码。但现在我想知道是否有任何方法可以导入python脚本,不是从文件导入,而是从包含python代码的变量导入 例如,如果这是纯文本代码,我如何使其正确执行: code = """ def M

我使用的是谷歌应用引擎,我试图基本上允许用户上传代码,稍后由服务器执行。我还必须能够将变量发送到脚本,这就是为什么最初在我运行桌面上的所有内容时,我会动态地导入所有内容(例如,脚本的名称存储在变量中)。但现在我不能这样做,因为谷歌应用程序引擎环境中有文件系统

我已经有一个数据库设置,这样我可以得到纯文本的代码。但现在我想知道是否有任何方法可以导入python脚本,不是从文件导入,而是从包含python代码的变量导入

例如,如果这是纯文本代码,我如何使其正确执行:

code = """
def Main(var):
    print "you entered: " + var
"""

首先,为代码创建一个模块:

# define module_name somewhere
import types
module = types.ModuleType(module_name)
您可能也想注册该模块:

import sys
sys.modules[module_name] = module
然后编译代码:

# source should the code to execute
# filename should be a pseudo-filename that the code's from
# (it doesn't actually have to exist; it's used for error messages)
code_object = compile(source, filename, 'exec')
然后在模块的上下文中执行代码对象:

exec code_object in module.__dict__

首先,为代码创建一个模块:

# define module_name somewhere
import types
module = types.ModuleType(module_name)
您可能也想注册该模块:

import sys
sys.modules[module_name] = module
然后编译代码:

# source should the code to execute
# filename should be a pseudo-filename that the code's from
# (it doesn't actually have to exist; it's used for error messages)
code_object = compile(source, filename, 'exec')
然后在模块的上下文中执行代码对象:

exec code_object in module.__dict__

感谢您的快速回复!如何将变量信息发送到此代码?对不起,让我重新表述一下。我如何使用variables@user1270285:
模块
在这一点上就像一个真正的模块。只需像通常调用模块中的函数那样调用它:
module。某些函数(var1,var2)
注册模块是否会使该模块在第一次运行后仍然可用?我相信您已经意识到这有多危险-您是用户,可能会做任何您能做的事情,如果你的应用程序只是执行代码。你必须真正信任你的用户。想象一下,有人删除了你的数据或烧掉了你的资源,因此你得到了一大笔账单。谢谢你的迅速回复!如何将变量信息发送到此代码?对不起,让我重新表述一下。我如何使用variables@user1270285:
模块
在这一点上就像一个真正的模块。只需像通常调用模块中的函数那样调用它:
module。某些函数(var1,var2)
注册模块是否会使该模块在第一次运行后仍然可用?我相信您已经意识到这有多危险-您是用户,可能会做任何您能做的事情,如果你的应用程序只是执行代码。你必须真正信任你的用户。想象一下,有人删除了你的数据,或者烧掉了你的资源,这样你就会得到一大笔账单。