# requirements.txt: necessary: six from six.moves import StringIO from .. import embeddedonly from embci.configs import DIR_BASE, DIR_DATA from embci.utils import (get_boolean, get_func_args, load_configs, get_config, mkuserdir, serialize, deserialize, config_logger, duration, validate_filename, LoggerStream, TempLogLevel, Singleton) # redirect logging stream to a StringIO so that we can check log messages logmsg = StringIO() logger = config_logger(level=logging.INFO, format='{message}', stream=logmsg, usecolor=False) def get_log_msg(f=logmsg): msg = f.getvalue() f.truncate(0) f.seek(0) # noqa: E702 return msg.strip() def test_serialization(): def bar(): ''' this function will be `embci.utils.bar` after deserialization with `method` set to `json`.
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import re import time import subprocess # requirements.txt: network: bottle import bottle from embci.utils import embedded_only, config_logger __basedir__ = os.path.dirname(os.path.abspath(__file__)) system = bottle.Bottle() logger = config_logger() @system.route('/') def system_index(): return '\n'.join(['<p>%s</p>' % s.strip() for s in __doc__.split('\n')]) def system_exec(cmd, block=True): '''This will block the caller thread until the command terminate''' proc = subprocess.Popen( cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) # Python 3 only # with proc: # code, output = proc.returncode, proc.stdout.read() if not block:
from embci.io import LSLReader as Reader, find_data_info, load_mat from embci.apps.recorder import Recorder from .model import Model # ============================================================================= # constants __basedir__ = os.path.dirname(os.path.abspath(__file__)) __layouts__ = os.path.join(__basedir__, 'layouts') __events__ = os.path.join(__basedir__, 'events.json') speller = bottle.Bottle() results = {} wslist = [] logger = config_logger(__name__) reader = model = event = outlet = wsevent = recorder = rec_lock = None # ============================================================================= # SSVEP WebUI EventIO @speller.route('/event/ws') def event_websocket(): ws = bottle.request.environ.get('wsgi.websocket') if ws is None: bottle.abort(400, 'WebSocket request expected.') wslist.append(ws) ADDR = '{REMOTE_ADDR}:{REMOTE_PORT}'.format(**ws.environ) logger.info('Event websocket connected from ' + ADDR) event_update() # Is this my turn?
def __external__(): ''' Importing inside this function to avoid the existance of useless module names as attributes of this module, resulting in a **clean** namespace. ''' # built-in import sys, functools, random, string, inspect # noqa: E401 from six import string_types # noqa: W611 from six.moves import ( # noqa: W611 socketserver, xmlrpc_client, xmlrpc_server, urllib, reduce, StringIO) # filter useless functions try: del xmlrpc_server.SimpleXMLRPCDispatcher.system_multicall del xmlrpc_server.SimpleXMLRPCDispatcher.register_multicall_functions del xmlrpc_server.SimpleXMLRPCRequestHandler.is_rpc_path_valid del xmlrpc_server.SimpleXMLRPCRequestHandler.accept_encodings del xmlrpc_server.SimpleXMLRPCRequestHandler.aepattern del xmlrpc_server.SimpleXMLRPCRequestHandler.decode_request_content except (AttributeError, NameError): pass # `embci.utils.jsonrpc` is part of project `EmBCI`, but it also can be # used individually like `import jsonrpc`. Functions below are not defined # inside this module and need to be imported from other library before # using them. To use `jsonrpc` outside `embci` package, just replace few # lines below with proper importing code to provide these functions. # e.g.: from simplejson import dumps, loads, ... from embci.utils import ( # noqa: W611 # jsonify/unjsonify method dumps, loads, # convert string to bytes and unicode, py 2 & 3 compatiable # e.g. ensure_bytes(u'\u963f') => b'\xe9\x98\xbf' ensure_bytes, ensure_unicode, # resolve arguments of a function # e.g. sum(x, y=None, z=1) => (['x', 'y', 'z'], (None, 1, )) get_func_args, # create logging.Logger, similar as logging.basicConfig # e.g. logger = config_logger(name='jsonrpc', format='%(message)s') config_logger, # a property only computed once and becomes a constant attribute CachedProperty, ) dumps = functools.partial(dumps, indent=None, separators=(',', ':')) params_types = (tuple, list, dict) logger_rpc = config_logger('JSONRPC', level='DEBUG', format='[%(asctime)s] %(name)s %(message)s', datefmt='%Y%m%d-%H:%M:%S', style='%') logger_server = config_logger('RPCServer', level='DEBUG') logger_rpc.setLevel('INFO') # default be quiet logger_server.setLevel('DEBUG') # default be verbose del config_logger namespace = dict( # utilities debug=lambda v=True: logger_rpc.setLevel('DEBUG' if v else 'INFO'), typename=lambda obj: type(obj).__name__, format_exc=lambda e: '%s: %s' % (type(e).__name__, e), random_id=lambda length=8: ''.join([ random.choice(string.ascii_lowercase + string.digits) for _ in range(length) ]), list_public_methods=lambda obj: [ method for method in dir(obj) if not method.startswith('_') and callable(getattr(obj, method)) ], resolve_dotted_attribute=lambda obj, attr, allow=True: reduce( getattr, [ i for i in (attr.split('.') if allow else [attr]) if not i.startswith('_') ], obj), # none represent no-exist, same as builtins.None none=type('NoExist', (), {}), # other modules, functions and instances imported/created above **locals()) import types module = types.ModuleType( __name__ + '.external', 'Virtual module that defines necessary external modules and functions') for _ in [ 'random', 'string', ]: namespace.pop(_, None) module.__dict__.update(namespace) return module