代码运行(1) 前提条件 在控制台完成沙箱模版创建。 在执行下文所有代码前,请先按照环境变量设置部分,完成环境变量设置。 运行代码 您可以使用 runcode 方法来在沙箱内置的 jupyter server 中执行代码。 python from e2bcodeinterpreter import Sandbox 注意:修改下面模版为您的模版名称或者模版id sandbox Sandbox.create(template"mytestcodetemplate") 默认执行python代码 response sandbox.runcode("print("hello")") 支持多种语言 您可以指定代码的语言,支持 python, javascript, java, r, bash。 python response sandbox.runcode( "console.log("hello")", "javascript" ) 创建代码执行上下文 默认情况下,每个语言会运行在其默认的上下文中,同一上下文共享变量。 您可以通过 createcodecontext 来创建上下文。 python ctx sandbox.createcodecontext(language"python") 您可以通过 context 参数来指定运行时上下文,需要注意,仅能设置 language 和 context 中的一个参数,两者互斥。 python response sandbox.runcode( "print("hello")", contextctx ) 代码执行流式返回 代码执行可以流式返回,您可以通过指定回调函数来接收流式返回的数据。 python pythonstreamcode """ import time for i in range(10): print(i, end'') time.sleep(1) """ sandbox.runcode( pythonstreamcode, onstdoutlambda data: print(data), onstderrlambda data: print(data), onresultlambda data: print(data), onerrorlambda data: print(data) ) 指定代码运行环境变量 您可以为代码运行指定环境变量。 python response sandbox.runcode( "print("hello")", envs{"foo": "bar"} ) 指定代码执行超时时间 您可以为代码运行指定超时时间,在超过指定时间后终止代码运行。 python response sandbox.runcode( "print("hello")", timeout60
来自: