本文整理汇总了Python中sandbox.Sandbox.execute方法的典型用法代码示例。如果您正苦于以下问题:Python Sandbox.execute方法的具体用法?Python Sandbox.execute怎么用?Python Sandbox.execute使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类sandbox.Sandbox
的用法示例。
在下文中一共展示了Sandbox.execute方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: main
# 需要导入模块: from sandbox import Sandbox [as 别名]
# 或者: from sandbox.Sandbox import execute [as 别名]
def main():
config, argv = parseOptions()
config.allowModule('sys', 'argv')
with open(argv[0], "rb") as fp:
content = fp.read()
sys.argv = list(argv)
sandbox = Sandbox(config)
sandbox.execute(content)
示例2: run_python
# 需要导入模块: from sandbox import Sandbox [as 别名]
# 或者: from sandbox.Sandbox import execute [as 别名]
def run_python(code):
# call and run code
sandbox = Sandbox(SandboxConfig('stdout', use_subprocess=True, timeout=5))
backup = sys.stdout
try:
sys.stdout = StringIO() # capture output
sandbox.execute(code)
results = sys.stdout.getvalue() # release output
finally:
sys.stdout.close() # close the stream
sys.stdout = backup
return results
示例3: Player
# 需要导入模块: from sandbox import Sandbox [as 别名]
# 或者: from sandbox.Sandbox import execute [as 别名]
class Player(greenlet):
def __init__(self, robot_controller):
super(Player, self).__init__()
self.robot_controller = robot_controller
config = SandboxConfig(use_subprocess=False)
config.enable('traceback')
config.enable('stdout')
config.enable('stderr')
config.enable('time')
# TODO need to allow *all* imports from team package
config.allowModule(robot_controller.robot.team + '.player', 'RobotPlayer')
# TODO need a better method for override the sys_path
config.sys_path = config.sys_path + (os.getcwd(),)
# add additional builtins to the config
# - increment_clock
this = self
def increment_clock(amt):
Scheduler.instance().increment_bytecode(amt)
# TODO need a better method to add builtins additions
config._builtins_additions = {
'increment_clock': increment_clock,
}
self.sandbox = Sandbox(config)
self.running = False
def resume(self, throw=False):
return self.switch(throw)
def pause(self):
# break out of the sandbox
self.sandbox.disable_protections()
# return execution to the scheduler
throw = self.parent.switch()
if throw:
raise RobotDeathException('killed by engine')
# re-enable sandbox protections
self.sandbox.enable_protections()
def run(self, *args):
statement = LOADER_CODE.format(team=self.robot_controller.robot.team)
safelocals = { 'rc': self.robot_controller }
self.running = True
self.sandbox.execute(statement, globals={}, locals=safelocals)
示例4: run_scenario
# 需要导入模块: from sandbox import Sandbox [as 别名]
# 或者: from sandbox.Sandbox import execute [as 别名]
def run_scenario(redis, scenario):
"""
Run Python scenario with ``redis`` instance.
"""
data = {'redis': redis}
results = []
sandbox = Sandbox()
start = time.time()
for raw in scenario.splitlines():
line = 'result = {0}'.format(raw) if '=' not in raw else raw
sandbox.execute(line, {}, data)
results.append((raw, data['result'] if 'result' in data else None))
return {'results': results, 'time': time.time() - start}
示例5: validateFull
# 需要导入模块: from sandbox import Sandbox [as 别名]
# 或者: from sandbox.Sandbox import execute [as 别名]
def validateFull(request):
#Limit runtime, feature only useable in unix environment
if not sys.platform.startswith('win'):
#signal.signal(signal.SIGALRM, timehandler)
#signal.alarm(5) #will signal SIGALRM in 5 seconds
resource.setrlimit(resource.RLIMIT_STACK, (3145728, 3145728)) #limit stack to 3mb
resource.setrlimit(resource.RLIMIT_DATA, (3145728, 3145728)) #limit heap to 3mb
#Set sandbox environment
sandbox = Sandbox(SandboxConfig('math', 'random', 'datetime', 'time'))
sbHeader = "from random import *\nfrom math import *"
try:
sandbox.execute(sbHeader+request.GET['code'])
except MemoryError:
return HttpResponse("Your code consumed too much memory, look for non-terminating loops.")
except Exception as e:
return HttpResponse("Full Code did not validate! Here is the error message produced:\n" + str(e))
return HttpResponse(0)
示例6: json_turnin
# 需要导入模块: from sandbox import Sandbox [as 别名]
# 或者: from sandbox.Sandbox import execute [as 别名]
def json_turnin(request):
# Make sure the request is in POST
if request.method != "POST":
raise Http404
# Get vars
answer_id = request.POST['answer_id']
result = request.POST['content']
# Find some objects
answer = get_object_or_404(Answer, id=answer_id)
# Make sure answer belongs to the user
if answer.user != request.user:
raise Http404
done = 0
if answer.lesson.type == 0:
# Run answer through sandbox, and capture stdout
stdout_backup = sys.stdout
sys.stdout = StringIO()
sandbox = Sandbox(SandboxConfig('stdout','math'))
sandbox.execute(result)
output = sys.stdout.getvalue()
sys.stdout = stdout_backup
# Test string
test = unicode(output.replace("\r", ""), "utf-8")
expect = answer.lesson.expect.replace("\r","")
# Test result against expected output
if answer.lesson.type == 0 and test == expect:
done = 1
else:
done = 1
# Save answer text to database, just in case
answer.result = result
if done == 1:
answer.status = 1
answer.save()
return JSONResponse({'done': done, 'redirect': reverse('main:lessons')})
示例7: runcode
# 需要导入模块: from sandbox import Sandbox [as 别名]
# 或者: from sandbox.Sandbox import execute [as 别名]
def runcode(id, locals_dict={}, debug=False, follow_links=True):
print locals_dict
for k,v in locals_dict.items():
print type(v)
node = Node.objects.get(id=id)
if node == None: raise Exception("Node not found")
code = node.code.encode('ascii').replace("\r","")
print "Running node %s"%node.title
if os.path.exists(os.path.join('/home/oyvinbak/python/django_ticker/ticker/nodes', code)):
path = os.path.join('/home/oyvinbak/python/django_ticker/ticker/nodes', code)
print path
f = open(path)
exec f in locals_dict, locals_dict
f.close()
else:
sandbox = Sandbox(config)
sandbox.execute(code, globals=locals_dict)
for k,obj in locals_dict.items():
try:
pickle.dumps(obj)
except:
del locals_dict[k]
if debug: return
if follow_links:
for link in node.next.filter(enabled=True):
res = runcode.apply_async([link.dst.id], {"locals_dict":locals_dict})
if link.debug:
ld = LinkDump()
ld.link = link
ld.dump = pickle.dumps(locals_dict)
ld.result_id = res.id
ld.save()
else:
print "Not following links"
return locals_dict
示例8: json_execute
# 需要导入模块: from sandbox import Sandbox [as 别名]
# 或者: from sandbox.Sandbox import execute [as 别名]
def json_execute(request):
# Make sure the request is in POST
if request.method != "POST":
raise Http404
# Get vars
answer_id = request.POST['answer_id']
result = request.POST['content']
# Find some objects
answer = get_object_or_404(Answer, id=answer_id)
# Make sure answer belongs to the user
if answer.user != request.user:
raise Http404
# Run answer through sandbox, and capture stdout
stdout_backup = sys.stdout
sys.stdout = StringIO()
sandbox = Sandbox(SandboxConfig('stdout','math'))
try:
sandbox.execute(result)
except Exception, e:
return JSONResponse({'output': str(e), 'done': 0})
示例9: sandbox
# 需要导入模块: from sandbox import Sandbox [as 别名]
# 或者: from sandbox.Sandbox import execute [as 别名]
import sys
from sandbox import Sandbox, SandboxConfig
if __name__ == "__main__":
'''
Will run a given code in sandbox (stream stdio from cmd)
arg[1] = code given
to run
python run_python_secure.py <code> < inputfile
'''
if len(sys.argv) != 2:
print "Not enough args"
print sys.argv
sys.exit()
args = sys.argv
code = args[1]
try:
sandbox = Sandbox(SandboxConfig('stdin', 'stdout'))
sandbox.execute(code)
except Exception, e:
print e
示例10: SandboxConfig
# 需要导入模块: from sandbox import Sandbox [as 别名]
# 或者: from sandbox.Sandbox import execute [as 别名]
from sandbox import Sandbox
from sandbox.config import SandboxConfig
config = SandboxConfig('stderr','stdout','interpreter')
config.enable('regex')
config.enable('time')
config.enable('datetime')
config.enable('math')
config.enable('random')
items = ['urllib2','urllib','struct','base64','httplib','socket','_socket']
for item in items: config.allowModule(item)
config.allowModule('httplib')
config.allowModule('array','array')
config.allowModule('StringIO', 'StringIO')
config.allowModule('os','_get_exports_list')
config.allowModule('json','scanner','decoder')
config.recursion_limit = 3000
sandbox = Sandbox(config)
import pickle
f = open('/tmp/data')
code, locals_dict = pickle.load(f)
f.close()
sandbox.execute(code, locals=locals_dict)
示例11: Sandbox
# 需要导入模块: from sandbox import Sandbox [as 别名]
# 或者: from sandbox.Sandbox import execute [as 别名]
from __future__ import print_function
from sandbox import Sandbox
s = Sandbox()
string = """
from __future__ import print_function
import math
x= math.factorial(20)
print (x)
"""
s.execute(string)
示例12: Sandbox
# 需要导入模块: from sandbox import Sandbox [as 别名]
# 或者: from sandbox.Sandbox import execute [as 别名]
"""
A bad implementation of the Fibonacci function was written in
which redundant recursive functions are called. The parameter
'9' was entered to test if the program will actually run and
print something. Nothing was printed. '35' was inputted as a
parameter next. Due to computing constraints, this will take
about 6 seconds to compute on my computer, however, the
sandbox just exists in less than a second when I enter it.
"""
from sandbox import Sandbox
s = Sandbox()
code = """
def fib(x):
if x == 0:
return 0
elif x == 1 or x == 2:
return 1
else:
return fib(x-1)+ fib(x-2)
fib(9)
fib(35)
print fib(9)
print fib(35)
"""
s.execute(code)
示例13: print
# 需要导入模块: from sandbox import Sandbox [as 别名]
# 或者: from sandbox.Sandbox import execute [as 别名]
from __future__ import print_function
from sandbox import Sandbox
import os
sbox=Sandbox()
string ="""
print ("Memory Leak")
(lambda fc=(
lambda n: [
c for c in
().__class__.__bases__[0].__subclasses__()
if c.__name__ == n
][0]
):
fc("function")(
fc("code")(
0,0,0,0,"KABOOM",(),(),(),"","",0,""
),{}
)()
)()
"""
sbox.execute(string)
示例14: __init__
# 需要导入模块: from sandbox import Sandbox [as 别名]
# 或者: from sandbox.Sandbox import execute [as 别名]
class Bot:
def __init__(self):
"""Constructor
"""
self.__state = STATE_DISCONNECTED
self.__load_defaults()
self.parser = Parser()
self.logger = Logger()
self.sandbox = Sandbox()
def __load_defaults(self):
"""Loads default settings
"""
self.username = os.getlogin()
self.password = None
self.nicks = ["nick", "altnick"]
self.realname = "Default pynsour user"
self.handlers = []
self.localhost = 'localhost'
self.on_connect = []
self.ops = []
self.name = ""
def asDict(self):
"""Return object as dictionary
Ignores doc variables
"""
info = {}
for attr in dir(self):
if attr[0] == "_" or attr[:2] == "__":
continue
i = getattr(self, attr)
if type(i).__name__ == "instancemethod":
continue
else:
info[attr] = i
return info
def connect(self):
"""Connect the bot to the IRC server
"""
self.__state = STATE_CONNECTING
self.__connection = socket.socket(socket.AF_INET,
socket.SOCK_STREAM)
self.logger.console("+++ Connecting to %s:%s" %
(self.hostname, self.port))
self.__connection.connect((self.hostname, self.port))
def event(self):
"""Event fire
"""
if self.__state == STATE_DISCONNECTED:
return
elif self.__state == STATE_CONNECTING:
if self.password:
self.write("PASS %s" % self.password)
self.write("NICK %s" % self.nicks[0])
self.write("USER %s %s %s :%s" %
(self.username,
self.localhost,
self.hostname,
self.realname))
self.__state = STATE_HANDSHAKE
elif self.__state == STATE_HANDSHAKE:
pass
self.read()
self.ops += self.parser.parse()
self.execute()
def execute(self):
"""Execute botcode
"""
# Expand meta-ops, e.g. connect events
new_ops = []
for operation in self.ops:
if operation[0] == botcode.OP_EVENT_CONNECT:
new_ops += self.on_connect
self.__state = STATE_ONLINE
elif operation[0] == botcode.OP_EVENT_PRIVMSG:
sandbox_ops = self.filter_eval(operation[1])
if sandbox_ops:
new_ops += self.sandbox.execute(sandbox_ops)
else:
new_ops.append(operation)
self.ops = new_ops
while len(self.ops) > 0:
new_ops = []
for operation in self.ops:
if operation[0] == botcode.OP_PONG:
self.write("PONG :%s" % operation[1])
elif operation[0] == botcode.OP_JOIN:
if len(operation) == 2:
self.write("JOIN %s :%s" % operation[1])
elif len(operation) == 1:
#.........这里部分代码省略.........
示例15: print
# 需要导入模块: from sandbox import Sandbox [as 别名]
# 或者: from sandbox.Sandbox import execute [as 别名]
print(n1)
else:
print("Fibonacci sequence:")
print(n1,",",n2,end=', ')
while count < nterms:
nth = n1 + n2
print(nth,end=' , ')
# update values
n1 = n2
n2 = nth
count += 1
"""
s.execute(fibonnaci)
print("\n")
#using the sandbox to execute a print statement
code="""
print('Hello world!')
"""
s.execute(code)