def monkey_compiler(self, *args, **kw): if self._body: # only do something if we have a body to play with if aq_parent(self) is None: # we have a body but no acquisiton context, # we're either something to do with an # FSPythonScript, or being called from within # __setstate__ due to a change in Python_magic or Script_magic # try and find an FSPythonScript in our call stack try: raise ZeroDivisionError except ZeroDivisionError: f = sys.exc_info()[2].tb_frame while f: obj = f.f_locals.get('self') if isinstance(obj,FSPythonScript): break f = f.f_back if f is None: filename = 'Python Script without Acquisition Context' else: filename = '/'.join(obj.getPhysicalPath()) else: filename = '/'.join(self.getPhysicalPath()) args = list(args) args[3]=filename return RestrictedPython.compile_restricted_function(*args, **kw)
def monkey_compiler(self, *args, **kw): if self._body: # only do something if we have a body to play with if aq_parent(self) is None: # we have a body but no acquisiton context, # we're either something to do with an # FSPythonScript, or being called from within # __setstate__ due to a change in Python_magic or Script_magic # try and find an FSPythonScript in our call stack try: raise ZeroDivisionError except ZeroDivisionError: f = sys.exc_info()[2].tb_frame while f: obj = f.f_locals.get("self") if isinstance(obj, FSPythonScript): break f = f.f_back if f is None: filename = "Python Script without Acquisition Context" else: filename = "/".join(obj.getPhysicalPath()) else: filename = "/".join(self.getPhysicalPath()) args = list(args) args[3] = filename return RestrictedPython.compile_restricted_function(*args, **kw)
def do_exec(args, kwargs): try: source_code = kwargs.get('source', '') source_cleaned = clean_code(source_code) locals_ = dict() response = dict() if RESTRICTION_OFF: with Capturing() as stdout: exec(source_cleaned, get_globals(), locals_) if len(stdout) > 0: response['stdout'] = '\n'.join(stdout) else: code = RestrictedPython.compile_restricted(source_cleaned, '<inline>', 'exec') # noqa exec(code, get_restricted_globals(), locals_) if '_print' in locals_: response['stdout'] = ''.join(locals_['_print'].txt) if 'return' in kwargs: if isinstance(kwargs['return'], list): data = dict() for variable in kwargs['return']: data[variable] = locals_.get(variable, None) else: data = locals_.get(kwargs['return'], None) response['data'] = nest.hl_api.serializable(data) return response except Exception as e: for line in traceback.format_exception(*sys.exc_info()): print(line, flush=True) abort(Response(str(e), EXCEPTION_ERROR_STATUS))
def set_pattern_function(self, key, source): 'Update and recompile a pattern function' def getitem(obj, index): if obj is not None and type(obj) in (list, tuple, dict): return obj[index] raise Exception() def getiter(obj): return obj restricted_globals = { '__builtins__': RestrictedPython.Guards.safe_builtins, '_print_': RestrictedPython.PrintCollector, '_getattr_': RestrictedPython.Guards.safer_getattr, '_getitem_': getitem, '_getiter_': getiter, '_write_': RestrictedPython.Guards.full_write_guard, 'math': math, 'random': random, 'palette': self._get_palette_color, 'palette_mirrored': self._get_palette_color_mirrored, 'hsv': animfunctions.ColorMode.hsv, 'rgb': animfunctions.ColorMode.rgb, 'clamp': utils.clamp, 'wave_pulse': driver.wave_pulse, 'wave_triangle': driver.wave_triangle, 'wave_sine': driver.wave_sine, 'wave_cubic': driver.wave_cubic, 'plasma_sines': driver.plasma_sines, 'plasma_sines_octave': driver.plasma_sines_octave, 'perlin_noise_3d': driver.perlin_noise_3d, 'fbm_noise_3d': driver.fbm_noise_3d, 'impulse_exp': utils.impulse_exp, 'fract': utils.fract, 'blackbody_to_rgb': driver.blackbody_to_rgb, 'blackbody_correction_rgb': driver.blackbody_correction_rgb, } restricted_locals = {} arg_names = ['t', 'dt', 'x', 'y', 'z', 'prev_state'] result = RestrictedPython.compile_restricted_exec(source) warnings = list(result.warnings) for name in result.used_names: if name not in restricted_globals and name not in arg_names: warnings.append(f'NameError: name \'{name}\' is not defined') if result.code: exec(result.code, restricted_globals, restricted_locals) if len(result.errors) == 0 and 'pattern' in restricted_locals: self._functions[key] = restricted_locals['pattern'] self._check_reset_animation_state() self._update_needed = True return result.errors, warnings
def _evalExp(self, exp, context): # protect context _context = copy.deepcopy(context) _context['_getattr_'] = self._hook_getattr _context['_getitem_'] = self._hook_getattr # _context = context # compile expressions try: code = RestrictedPython.compile_restricted(exp, '<string>', 'eval') except: raise RuntimeError('ERROR import expression') return eval(code, _context)
def compile_pattern(self, source): """ Compiles source string to a pattern function using restricted globals. """ def getitem(obj, index): if obj is not None and type(obj) in (list, tuple, dict): return obj[index] raise Exception() def getiter(obj): return obj restricted_globals = { '__builtins__': RestrictedPython.Guards.safe_builtins, '_print_': RestrictedPython.PrintCollector, '_getattr_': RestrictedPython.Guards.safer_getattr, '_getitem_': getitem, '_getiter_': getiter, '_write_': RestrictedPython.Guards.full_write_guard, 'math': math, 'random': random, 'hsv': patterns.ColorMode.hsv, 'rgb': patterns.ColorMode.rgb, 'clamp': utils.clamp, 'wave_pulse': rpi_ws281x.wave_pulse, 'wave_triangle': rpi_ws281x.wave_triangle, 'wave_sine': rpi_ws281x.wave_sine, 'wave_cubic': rpi_ws281x.wave_cubic, 'plasma_sines': rpi_ws281x.plasma_sines, 'plasma_sines_octave': rpi_ws281x.plasma_sines_octave, 'perlin_noise_3d': rpi_ws281x.perlin_noise_3d, 'impulse_exp': utils.impulse_exp, 'fract': utils.fract, 'blackbody_to_rgb': rpi_ws281x.blackbody_to_rgb, 'blackbody_correction_rgb': rpi_ws281x.blackbody_correction_rgb, } restricted_locals = {} arg_names = ['t', 'dt', 'x', 'y', 'prev_state'] name_error = False results = RestrictedPython.compile_restricted_exec(source, filename='<inline code>') print(results) warnings = list(results.warnings) for name in results.used_names: if name not in restricted_globals and name not in arg_names: name_error = True warnings.append('NameError: name \'{}\' is not defined'.format(name)) if results.code: exec(results.code, restricted_globals, restricted_locals) return results.errors, warnings, restricted_locals['pattern'] else: return results.errors, warnings, None
def udfize_def(code: str, glbCtx: dict = None, lclCtx: dict = None): if glbCtx is None: glbCtx = LuciUdfRegistry.get_safe_globals() if lclCtx is None: lclCtx = {} udf = LuciUdfRegistry.udfize_def_string(code) udf_ast = ast.parse(udf, filename="<udf>") result = rp.compile_restricted(udf_ast, filename="<string>", mode="exec") exec(result, glbCtx, lclCtx) return lclCtx["udf"]
def route_exec(): """ Route to execute script in Python. """ try: args, kwargs = get_arguments(request) source_code = kwargs.get('source', '') source_cleaned = clean_code(source_code) locals = dict() response = dict() if RESTRICTION_OFF: with Capturing() as stdout: exec(source_cleaned, get_globals(), locals) if len(stdout) > 0: response['stdout'] = '\n'.join(stdout) else: code = RestrictedPython.compile_restricted(source_cleaned, '<inline>', 'exec') exec(code, get_restricted_globals(), locals) if '_print' in locals: response['stdout'] = ''.join(locals['_print'].txt) if 'return' in kwargs: if isinstance(kwargs['return'], list): data = dict() for variable in kwargs['return']: data[variable] = locals.get(variable, None) else: data = locals.get(kwargs['return'], None) response['data'] = nest.hl_api.serializable(data) return jsonify(response) except nest.kernel.NESTError as e: print('NEST error: {}'.format(e)) abort(Response(getattr(e, 'errormessage'), NEST_ERROR_STATUS)) except Exception as e: print('Error: {}'.format(e)) abort(Response(str(e), EXCEPTION_ERROR_STATUS))
def _compiler(self, *args, **kw): return RestrictedPython.compile_restricted_function(*args, **kw)
def getitem(obj, index): if obj is not None and type(obj) in (list, tuple, dict): return obj[index] raise Exception() restricted_globals = { '__builtins__': RestrictedPython.Guards.safe_builtins, '_print_': RestrictedPython.PrintCollector, '_getattr_': RestrictedPython.Guards.safer_getattr, '_getitem_': getitem, '_write_': RestrictedPython.Guards.full_write_guard, 'math': math, 'random': random, } restricted_locals = {} source_code = """ def pattern(t, dt, x, y, prev_state): return (t + x, 0, prev_state[0]) """ byte_code = RestrictedPython.compile_restricted_exec(source_code, filename='<inline code>') print(byte_code) print(exec(byte_code[0], restricted_globals, restricted_locals)) print(restricted_locals['pattern'](0.5, 0.01, 0.2, 0.2, (1, 2)))
def compile(self, source, name, elevated=False): return RestrictedPython.compile_restricted(source, name, 'exec', elevated=elevated)