def saveSettings(self, settings): settings.setValue('splitter', self.splitter.saveState()) settings.setValue('presets', self.presetdict) settings.beginGroup('views') settings.remove('') for view in self.views: settings.setValue(view.name, pickle.dumps(view.dlginfo)) settings.endGroup()
def test_pickable(): store = {'phi': 3.1415926535897931, 'type': 'e', 'dx': 400, 'chi': 0.0, 'theta': -0.17453292519943295, 'omega': 0.0} hw = None pos = residevice.position.PositionFromStorage(hw, store) proxied = residevice.ResiPositionProxy(pos) res = pickle.dumps(proxied, protocol=0) restored = pickle.loads(res) print(store) print(restored.storable()) assert restored.storable() == store
def test_readonly_objects(): d = readonlydict({'a': 1, 'b': 2}) assert raises(TypeError, d.update, {}) # pickle Protocoll 0 unpickled = pickle.loads(pickle.dumps(d)) assert isinstance(unpickled, readonlydict) assert len(unpickled) == 2 # pickle Protocoll 2 unpickled = pickle.loads(pickle.dumps(d, 2)) assert isinstance(unpickled, readonlydict) assert len(unpickled) == 2 l = readonlylist([1, 2, 3]) assert raises(TypeError, l.append, 4) # pickle Protocoll 0 unpickled = pickle.loads(pickle.dumps(l)) assert isinstance(unpickled, readonlylist) assert len(unpickled) == 3 # pickle Protocoll 2 unpickled = pickle.loads(pickle.dumps(l, 2)) assert isinstance(unpickled, readonlylist) assert len(unpickled) == 3
def cache_dump(obj): res = [] if isinstance(obj, repr_types): res.append(repr(obj)) elif isinstance(obj, list): res.append('[') for item in obj: res.append(cache_dump(item)) res.append(',') res.append(']') elif isinstance(obj, tuple): res.append('(') for item in obj: res.append(cache_dump(item)) res.append(',') res.append(')') elif isinstance(obj, dict): res.append('{') for key, value in iteritems(obj): res.append(cache_dump(key)) res.append(':') res.append(cache_dump(value)) res.append(',') res.append('}') elif isinstance(obj, frozenset): res.append('{') for item in obj: res.append(cache_dump(item)) res.append(',') res.append('}') elif obj is None: return 'None' else: try: resstr = 'cache_unpickle("' + \ from_utf8(b64encode(pickle.dumps(obj, protocol=0))) + '")' res.append(resstr) except Exception as err: raise ValueError('unserializable object: %r (%s)' % (obj, err)) return ''.join(res)
def serialize_ok_reply(self, payload): return pickle.dumps(payload, 2)
def serialize_cmd(self, cmdname, args): return pickle.dumps(args, 2)
def _serialize_default(self, obj): return {'__pickle__': pickle.dumps(obj, 2).decode('latin1')}
def serialize_event(self, evtname, payload): return pickle.dumps(payload, 2)
def serialize_error_reply(self, reason): return pickle.dumps(reason, 2)
def serialize(data): return pickle.dumps(data, 2)
def _target(self, sandbox, uuid, code, setups, user, emitter, args, quiet): socket = nicos_zmq_ctx.socket(zmq.DEALER) poller = zmq.Poller() poller.register(socket, zmq.POLLIN) if sandbox: # create a new temporary directory for the sandbox helper to # mount the filesystem tempdir = tempfile.mkdtemp() rootdir = path.join(tempdir, 'root') os.mkdir(rootdir) # since the sandbox does not have TCP connection, use a Unix socket sockname = 'ipc://' + path.join(tempdir, 'sock') socket.bind(sockname) prefixargs = [sandbox, rootdir, str(os.getuid()), str(os.getgid())] else: port = socket.bind_to_random_port('tcp://127.0.0.1') sockname = 'tcp://127.0.0.1:%s' % port prefixargs = [] scriptname = path.join(config.nicos_root, 'bin', 'nicos-simulate') userstr = '%s,%d' % (user.name, user.level) if quiet: args.append('--quiet') if config.sandbox_simulation_debug: args.append('--debug') proc = createSubprocess(prefixargs + [ sys.executable, scriptname, sockname, uuid, ','.join(setups), userstr, code ] + args) if sandbox: if not session.current_sysconfig.get('cache'): raise NicosError('no cache is configured') socket.send(pickle.dumps(session.cache.get_values())) else: # let the subprocess connect to the cache socket.send(b'') while True: res = poller.poll(500) if not res: if proc.poll() is not None: if emitter: request = emitter.current_script() if request.reqid == uuid: request.setSimstate('failed') request.emitETA(emitter._controller) if not quiet: session.log.warning('Dry run has terminated ' 'prematurely') return continue msgtype, msg = unserialize(socket.recv()) if msgtype == SIM_MESSAGE: if emitter: emitter.emit_event('simmessage', msg) else: record = logging.LogRecord(msg[0], msg[2], '', 0, msg[3], (), None) record.message = msg[3].rstrip() session.log.handle(record) elif msgtype == SIM_BLOCK_RES: if emitter: block, duration, uuid = msg request = emitter.current_script() if request.reqid == uuid: request.updateRuntime(block, duration) elif msgtype == SIM_END_RES: if emitter: if not quiet: emitter.emit_event('simresult', msg) request = emitter.current_script() if request.reqid == uuid: request.setSimstate('success') request.emitETA(emitter._controller) # In the console session, the summary is printed by the # sim() command. socket.close() break # wait for the process, but only for 5 seconds after the result # has arrived wait_start = time.time() try: # Python 3.x has a timeout argument for poll()... while time.time() < wait_start + 5: if proc.poll() is not None: break else: raise Exception('did not terminate within 5 seconds') except Exception: session.log.exception('Error waiting for dry run process') if sandbox: try: os.rmdir(rootdir) os.rmdir(tempdir) except Exception: pass
def _add_preset(self, name, info): if name: self.presetdict[name] = pickle.dumps(info) self._refresh_presets()