class ChatClient(Socket): log = smartlog.Smartlog() def __init__(self, name): super().__init__('box.local', 50007, name=name) self.log.printname = True self.run() def listener(self): while True: x = self.read() self.log.name = x['from'] self.log.logn(x['date'] + ': ' + x['content']) def talker(self): while True: x = self.log.prompt('msg') self.write({ 'from': self.name, 'content': x, 'date': quickdate('now') }) def run(self): self.write({ 'from': self.name, 'content': 'logged in', 'date': quickdate('now') }) listener = threading.Thread(target=self.listener, args=()) listener.run() self.talker()
class SmartlogServer(Server): log = smartlog.Smartlog() def postproc(self, args): self.log.printname = True for k in self.data[args['id']]: self.log.name = k self.log.info("%s" % (self.data[args['id']][k])) return args
def runcmd(self, sock, key, data): cmd = data['cmd'] import subprocess p = subprocess.Popen(cmd.split(" "), shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE) log = smartlog.Smartlog() log.name = key log.printname = True stdout, stderr = p.communicate() for line in stdout.decode().split('\n')[:-1]: log.logok(line)
class ChatServer(Server): log = smartlog.Smartlog() def __init__(self): super().__init__('box.local', 50007) def postproc(self, args): msg = self.data[args['id']] for w in self.wx: if w != self: w.write(msg) print(msg) sock = args['socket'] return args
class KeyBindings(): log = smartlog.Smartlog() def __init__(self, bindings=None): if bindings == None: self.bindings = { 'q': (sys.exit, None), } else: self.bindings = bindings # Add a keybinding by supplying key, callback, arg def add(self, key, callback, args): self.bindings[key] = (callback, args) # Allow multiple iterations of key command; supports numbers def accumulate(self, key): num = "" while key.isdigit(): num += key key = getch.getch() for i in range(int(num)): self.handle(key) # Handle keybinding def handle(self, key): if key.isdigit(): self.accumulate(key) if key not in self.bindings: return False (callback, args) = self.bindings[key] if args == None: return callback() else: return callback(args) # Show key and function name def legend(self): str = "" for key in self.bindings: str += " " + key + ": " + self.bindings[key][0].__name__ + '\n' return str # Wait for keypress, and handle def wait(self): key = getch.getch() return (key, self.handle(key))
def __init__(self, name='dataserver'): self.name = name self.log = smartlog.Smartlog()
class AutoCompleter(): words = [] suggestion = "" last = "" input = "" finished = False prompt = "" prints = True log = smartlog.Smartlog() def __init__(self, words=[]): self.words += words def consume(self, key): if ord(key) == 127: self.input = self.input[:-1] elif key == "\x17": parts = self.input.split(" ") self.input = " ".join(parts[:-1]) elif key in "=-';:.,<>/?][{}\|)(!@#$%^&*~_`": if self.suggestion: self.input += self.suggestion + key else: self.input += key elif key == '\t': if self.suggestion: self.input += ' ' elif key == '\x0e' or key == '\x06': pass elif key == '\n': if self.suggestion: self.input += self.suggestion self.finished = True elif key == ' ': if self.suggestion: self.input += self.suggestion + ' ' else: self.input += key elif key.isalnum(): self.input += key else: pass if self.prints: self.log.reprint(self.prompt + self.input) def autocomplete(self): if self.finished: self.suggestion = None return lastword = self.input.split(" ")[-1] lastword = ''.join(e for e in lastword if e.isalnum()) if lastword != "": for word in self.words: if word.startswith(lastword): self.suggestion = word[len(lastword):] if self.input + self.suggestion == self.last: continue self.last = self.input + self.suggestion return self.suggestion = None def formatsuggestion(self): if self.suggestion: return (self.prompt + self.input + self.log.t.italic(self.suggestion)) else: return self.prompt + self.input def printsuggestion(self): if self.suggestion: self.log.reprint(self.formatsuggestion()) def handle(self, key): self.consume(key) self.autocomplete() if self.prints: self.printsuggestion() else: return self.formatsuggestion() def run(self): self.finished = False self.input = "" self.log.outfile.write(self.prompt) self.log.outfile.flush() while not self.finished: key = getch.getch() self.handle(key) self.log.outfile.write('\n') return self.input
import socket import json import smartlog import select import binascii import threading import os, sys import queue from toolbelt.quickdate import quickdate import smartlog log = smartlog.Smartlog() ######################################## #! My Socket class for easier sockets ######################################## class Socket: name = "" sock = None plug = None def __init__(self, host, port, lhost='localhost', lport=0, name="", init=True): self.config(host, port, lhost, lport, name)
class Interpreter: auto = keybindings.AutoCompleter() log = smartlog.Smartlog() commands = {} def help(self): description = {} for key in self.commands: if 'opts' in self.commands[key]: if 'help' in self.commands[key]['opts']: description[key] = self.commands[key]['opts']['help'] self.log.logdata({'data': description}) def quit(self): sys.exit(0) def __init__(self, commands=None): if not self.commands: self.commands = {} self.commands.update({ 'help': { 'func': self.help, 'args': None, 'opts': { 'help': 'print this info' } }, 'quit': { 'func': self.quit, 'args': None, 'opts': { 'log': 'Quitting program', 'help': 'quit program' } } }) if commands: self.commands.update(commands) # Handle command def handle(self, args): adf = args['argspec'] import pandas try: cn = adf.loc[adf['key'] == 'cmd'].iloc[0]['data'] action = self.commands[cn] dogather = False if action['args']: for arg in action['args']: idx = adf[adf['key'] == arg].index.to_list() adf.optional.loc[idx] = False if pandas.isnull(adf.data.loc[idx]).any(): dogather = True args['argspec'] = adf if dogather: args = self.log.gather(args) #self.log.print(args); args = self.preprocess({ 'argspec': args['argspec'], 'data': args['data'], 'auto': args['auto'], 'xs': args['xs'] }) if 'args' in action: if not action['args']: args = None except KeyError as e: self.log.warn("Command not found: %s" % (cn)) self.log.warn("Exception: %s" % (e)) return args except Exception: import traceback traceback.print_exc() import code code.interact(local=locals()) args = self.log.exlog(callback=action['func'], args=args, opts=action['opts']) args = self.log.exlog(callback=self.postprocess, args=args) return args def preprocess(self, args): return args def postprocess(self, args): return args def run(self, xs=None): while True: args = self.log.gather({ 'argspec': self.argspec, 'keys': ['cmd'], 'xs': xs, 'auto': self.auto, 'words': True }) args = self.handle(args) xs = []
def __init__(self, config=None, table=''): self.config = config; self.table = table; self.log = smartlog.Smartlog();
class Poller: log = smartlog.Smartlog() def __init__(self, args=None): q = queue.Queue() self.args = [{ 'queue': q, 'naptime': '3 seconds', 'count': 6, 'function': self.testproducer, }, { 'queue': q, 'naptime': '2 seconds', 'count': 10, 'function': self.testproducer, }, { 'queue': q, 'naptime': '1 seconds', 'until': '25 seconds', 'function': self.testconsumer, }] if args: self.args = args def testproducer(self, args): args['queue'].put("%s %s" % (args['threadnum'], args['counter'])) return args def testconsumer(self, args): msg = args['queue'].get() self.log.print(msg) return args def execute(self, args): args = args['function'](args) time.sleep(args['naptime']) args['counter'] += 1 return args def pollthread(self, args): self.finished = False if 'naptime' not in args: args['naptime'] = 1 args['counter'] = 0 if 'count' in args: while args['counter'] < args['count']: args = self.execute(args) elif 'until' in args: now = toolbelt.quickdate.QuickDate() until = toolbelt.quickdate.QuickDate(args['until']) while now.before(until): args = self.execute(args) now.set() else: while True: args = self.execute(args) args['queue'].task_done() def poll(self, args=None): if not args: args = self.args ts = [] qs = [] threadno = 1 for arg in args: arg['threadnum'] = threadno t = threading.Thread(target=self.pollthread, args=(arg, )) ts.append(t) if 'queue' in arg: if arg['queue'] not in qs: qs.append(arg['queue']) threadno += 1 for t in ts: t.start() for q in qs: q.join()