def __init__(self, options): self.name = self.__cmd_name__ self.version = self.__cmd_ver__ self.tags = self.__cmd_tags__ self._options = options if not REGEX_COMMAND_NAME.match(self.name): raise PyCoCommandMalformedException( 'Malformed command name: "{0}"'.format(self.name)) assert len( self.name ) <= 15, 'Command name: "{0}" is longer than 15 char'.format(self.name) self._parser = self.add_args() # try to automatically add 'version' option if not # already done by the child class # NOTE if you get errors here maybe you want to user # a conflict_handler https://docs.python.org/2/library/argparse.html#conflict-handler try: self._parser.add_argument('--version', dest='version', action='store_true', help='Show version.') except Exception as e: pass # add epilog to the parser if not already done by the child # class if self._parser.epilog is None: self._parser.epilog = '{0} ({1})'.format(self.name, self.version) self._options, unknown_options = self._parser.parse_known_args(options) if unknown_options: disp('Unknown options: {0}'.format(', '.join(unknown_options)))
def __init__(self, options): self.name = self.__cmd_name__ self.version = self.__cmd_ver__ self.tags = self.__cmd_tags__ self._options = options if not REGEX_COMMAND_NAME.match(self.name): raise PyCoCommandMalformedException('Malformed command name: "{0}"'.format(self.name)) assert len(self.name) <= 15, 'Command name: "{0}" is longer than 15 char'.format(self.name) self._parser = self.add_args() # try to automatically add 'version' option if not # already done by the child class # NOTE if you get errors here maybe you want to user # a conflict_handler https://docs.python.org/2/library/argparse.html#conflict-handler try: self._parser.add_argument('--version', dest='version', action='store_true', help='Show version.') except Exception as e: pass # add epilog to the parser if not already done by the child # class if self._parser.epilog is None: self._parser.epilog = '{0} ({1})'.format(self.name, self.version) self._options, unknown_options = self._parser.parse_known_args(options) if unknown_options: disp('Unknown options: {0}'.format(', '.join(unknown_options)))
def add(command_name, command_class, command_options): if command_name in CommandResolver._command_map: disp('Command "{0}" has been overridden by class "{1}"'.format( command_name, command_class.__name__), color='red') CommandResolver._command_map[command_name] = (command_class, command_options)
def impl(self): try: with open(os.path.abspath(self.get_options().file), 'rb') as fin: for line in fin.readlines(): disp(line, end='') except Exception as e: disp('Exception: {0}'.format(sys.exc_info()[0]), color='red') return 1 return 0
def impl(self): try: with open(os.path.abspath(self.get_options().file), 'rb') as fin: for line in fin.readlines(): disp(line, end='') except Exception as e: disp('Exception: {0}'.format(sys.exc_info()[0]), color='red') return 1 return 0
def wrapped_f(*args): if GlobalVariables.get_instance().get('timeit_commands') != 'True': return f(*args) ts = time.time() r = f(*args) te = time.time() disp('\n= Executed in {0:.3f} secs ='.format(te - ts), color='yellow') return r
def impl(self): if self.get_options().start: GlobalVariables.get_instance().set(Time.GLOBAL_VAR_NAME, time.time(), level='_internal') return 0 if self.get_options().stop: delta = time.time() - GlobalVariables.get_instance().get(Time.GLOBAL_VAR_NAME, level='_internal') disp('Elapsed time: {0:.3f} secs ='.format(delta)) return 0 disp(datetime.now().strftime('%A %Y-%m-%d %H:%M:%S.%f %Z')) return 0
def get_values(values): vals = [] for v in values: for num in v.split(','): if num.strip(): try: vals.append(float(num.strip())) except Exception as e: disp('Value: {0} is not a valid number'.format(num), color='red') return vals
def impl(self): # import here to avoid circular deps from pyco.core.resolver import CommandResolver reverse = self.get_options().r commands_list = CommandResolver.get_instance().get_command_names_and_details() disp('{0: <16}{1}'.format('Name:', 'Tags:')) for command, tags, hidden in sorted(commands_list, key=lambda tup: tup[0], reverse=reverse): if not hidden: disp('{0: <16}{1}'.format(command, ','.join(sorted(tags)))) return 0
def impl(self): try: with open(os.path.abspath(self.get_options().file), 'rb') as fin: lines = tail(fin, lines=self.get_options().n).split('\n') if self.get_options().r: lines = lines.reverse() for line in lines: disp(line) except Exception as e: disp('Exception: {0}'.format(sys.exc_info()[0]), color='red') return 1 return 0
def impl(self): try: with open(os.path.abspath(self.get_options().file), 'rb') as fin: lines = tail(fin, lines=self.get_options().n).split('\n') if self.get_options().r: lines = lines.reverse() for line in lines: disp(line) except Exception as e: disp('Exception: {0}'.format(sys.exc_info()[0]), color='red') return 1 return 0
def impl(self): if self.get_options().start: GlobalVariables.get_instance().set(Time.GLOBAL_VAR_NAME, time.time(), level='_internal') return 0 if self.get_options().stop: delta = time.time() - GlobalVariables.get_instance().get( Time.GLOBAL_VAR_NAME, level='_internal') disp('Elapsed time: {0:.3f} secs ='.format(delta)) return 0 disp(datetime.now().strftime('%A %Y-%m-%d %H:%M:%S.%f %Z')) return 0
def impl(self): # import here to avoid circular deps from pyco.core.resolver import CommandResolver reverse = self.get_options().r commands_list = CommandResolver.get_instance( ).get_command_names_and_details() disp('{0: <16}{1}'.format('Name:', 'Tags:')) for command, tags, hidden in sorted(commands_list, key=lambda tup: tup[0], reverse=reverse): if not hidden: disp('{0: <16}{1}'.format(command, ','.join(sorted(tags)))) return 0
def impl(self): # import here to avoid circular deps from pyco.core.parser import CommandParser from pyco.core.resolver import CommandResolver alias = self.get_options().name cmd_name, options = CommandParser.parse(self.get_options().command) disp('{0}, {1}, {2}'.format(alias, cmd_name, options)) cmd_class, _, _ = CommandResolver.get_instance().resolve(cmd_name) if cmd_class is None: disp('Invalid alias: "{0}" is unknown.'.format(cmd_name), color='red') return 1 CommandResolver.get_instance().add(alias, cmd_class, options) return 0
def impl(self): # import here to avoid circular deps from pyco.core.parser import CommandParser from pyco.core.resolver import CommandResolver alias = self.get_options().name cmd_name, options = CommandParser.parse(self.get_options().command) disp('{0}, {1}, {2}'.format(alias, cmd_name, options)) cmd_class, _, _ = CommandResolver.get_instance().resolve(cmd_name) if cmd_class is None: disp('Invalid alias: "{0}" is unknown.'.format(cmd_name), color='red') return 1 CommandResolver.get_instance().add(alias, cmd_class, options) return 0
def impl(self): path = self.get_options().path.strip() if not path: disp('path is empty', color='red') return 1 if path == '..': os.chdir(os.path.split(os.getcwd())[0]) return 0 elif path == '/': os.chdir('/') return 0 else: try: os.chdir(os.path.abspath(path)) except Exception as e: disp(e, color='red') return 1 return 0
def impl(self): path = self.get_options().path.strip() if not path: disp('path is empty', color='red') return 1 if path == '..': os.chdir(os.path.split(os.getcwd())[0]) return 0 elif path == '/': os.chdir('/') return 0 else: try: os.chdir(os.path.abspath(path)) except Exception as e: disp(e, color='red') return 1 return 0
def impl(self): if self.get_options().reset: StdoutRedirect.get_instance().reset() return 0 if self.get_options().mode and self.get_options().file: if self.get_options().mode not in ['wb', 'ab']: disp('Value: "{0}" is not valid for argument --mode.'.format(self.get_options().mode)) return 1 if not self.get_options().file: disp('Filename: "{0}" is not valid for argument --file.'.format(self.get_options().file)) return 1 StdoutRedirect.get_instance().to_file(os.path.abspath(self.get_options().file), mode=self.get_options().mode) return 0 if self.get_options().buffer: print('to_buffer') StdoutRedirect.get_instance().to_buffer() return 0
def impl(self): if self.get_options().reset: StdoutRedirect.get_instance().reset() return 0 if self.get_options().mode and self.get_options().file: if self.get_options().mode not in ['wb', 'ab']: disp('Value: "{0}" is not valid for argument --mode.'.format( self.get_options().mode)) return 1 if not self.get_options().file: disp( 'Filename: "{0}" is not valid for argument --file.'.format( self.get_options().file)) return 1 StdoutRedirect.get_instance().to_file(os.path.abspath( self.get_options().file), mode=self.get_options().mode) return 0 if self.get_options().buffer: print('to_buffer') StdoutRedirect.get_instance().to_buffer() return 0
def impl(self): files = sorted(os.listdir(os.getcwd())) _f = [f for f in files if os.path.isfile(os.path.join(os.getcwd(), f))] _d = [f for f in files if os.path.isdir(os.path.join(os.getcwd(), f))] _l = [] byte_size = 0 for items in [_d, _f]: for item in items: stat = os.stat(item) _l.append((stat.st_gid, stat.st_uid, stat.st_mode, datetime.fromtimestamp(stat.st_ctime).strftime('%Y-%m-%d %H:%M:%S'), stat.st_size, item)) if len(str(stat.st_size)) > byte_size: byte_size = len(str(stat.st_size)) + 1 disp('{0:<4} {1:<4} {2:<6} {3:<20} {4:<{6}} {5}'.format('GId:', 'UId:', 'Mode:', 'Date:', 'Size:', 'Name:', byte_size)) for gid, uid, mode, dt, size, name in _l: disp('{0:<4} {1:<4} {2:<6} {3:<20} {4:<{6}} {5}'.format(gid, uid, mode, dt, size, name, byte_size)) return 0
def impl(self): files = sorted(os.listdir(os.getcwd())) _f = [f for f in files if os.path.isfile(os.path.join(os.getcwd(), f))] _d = [f for f in files if os.path.isdir(os.path.join(os.getcwd(), f))] _l = [] byte_size = 0 for items in [_d, _f]: for item in items: stat = os.stat(item) _l.append((stat.st_gid, stat.st_uid, stat.st_mode, datetime.fromtimestamp( stat.st_ctime).strftime('%Y-%m-%d %H:%M:%S'), stat.st_size, item)) if len(str(stat.st_size)) > byte_size: byte_size = len(str(stat.st_size)) + 1 disp('{0:<4} {1:<4} {2:<6} {3:<20} {4:<{6}} {5}'.format( 'GId:', 'UId:', 'Mode:', 'Date:', 'Size:', 'Name:', byte_size)) for gid, uid, mode, dt, size, name in _l: disp('{0:<4} {1:<4} {2:<6} {3:<20} {4:<{6}} {5}'.format( gid, uid, mode, dt, size, name, byte_size)) return 0
def impl(self): if self.get_options().list: name, value = GlobalVariables.get_instance().get_all() spacing = len(max(name, key=len)) disp('{0: <{1}} {2}'.format('Name:', spacing, 'Value:')) for n, v in sorted(zip(name, value)): disp('{0: <{1}} = {2}'.format(n, spacing, v)) return 0 if self.get_options().echo is not None: disp(GlobalVariables.get_instance().get(self.get_options().echo)) return 0 if self.get_options().unset is not None: GlobalVariables.get_instance().unset(self.get_options().unset) return 0 else: GlobalVariables.get_instance().set(self.get_options().name, ' '.join(self.get_options().value)) # disp('{0} = {1}'.format(self.get_options().name, GlobalVariables.get_instance().get(self.get_options().name))) # noqa return 0
def impl(self): if self.get_options().list: name, value = GlobalVariables.get_instance().get_all() spacing = len(max(name, key=len)) disp('{0: <{1}} {2}'.format('Name:', spacing, 'Value:')) for n, v in sorted(zip(name, value)): disp('{0: <{1}} = {2}'.format(n, spacing, v)) return 0 if self.get_options().echo is not None: disp(GlobalVariables.get_instance().get(self.get_options().echo)) return 0 if self.get_options().unset is not None: GlobalVariables.get_instance().unset(self.get_options().unset) return 0 else: GlobalVariables.get_instance().set( self.get_options().name, ' '.join(self.get_options().value)) # disp('{0} = {1}'.format(self.get_options().name, GlobalVariables.get_instance().get(self.get_options().name))) # noqa return 0
def impl(self): opts = self.get_options() if not opts.x: disp('x is empty', color='red') return 1 if not opts.y: disp('y is empty', color='red') return 1 x_values = get_values(opts.x) y_values = get_values(opts.y) if len(x_values) != len(y_values): disp('Size mismatch: x = {0}, y = {1}'.format(len(x_values), len(y_values)), color='red') return 1 chart = pygal.Line(width=opts.width, height=opts.height, explicit_size=True) chart.title = 'Plot' chart.x_labels = x_values chart.add('data', y_values) if opts.browser: chart.render_in_browser() if opts.file: chart.render_to_png(opts.file) return 0
def run(self): disp('{0} {1}'.format(self.name, self.get_options()), debug=True) if self.get_options().version: disp('{0} {1}'.format(self.name, self.version)) return 1 return self.impl()
def main(): command_resolver = CommandResolver.get_instance() history = History.get_instance() disp('Loading config...') try: ConfigLoader('.config') except Exception as e: disp('ConfigLoader: {0}'.format(e), color='red') disp('Loading aliases...') try: AliasLoader() except Exception as e: disp('AliasLoader: {0}'.format(e), color='red') infinite_loop = True while infinite_loop: disp(Prompt().show(), color='blue', end='') command_str = get_input().strip() if not command_str: continue history.append(command_str) command_pipe = command_resolver.resolve(command_str) for cmd_class, options, suggested_cmd in command_pipe: disp('cmd_class: {0} options: {1} suggested_cmd: {2}'.format( cmd_class, options, suggested_cmd), debug=True) if cmd_class is not None: try: # if the PycoStringBuffer is not empty means that | or || # has been used if PycoStringBuffer.get() and len(command_pipe) > 1: options.append(PycoStringBuffer.get()) r = cmd_class(options).run() if r != 0: disp('Command "{0}" finished with exit code: {1}'. format(cmd_class.__cmd_name__, r), color='red') # see parser '&' definition if _GV_.get('pyco_unconditional_execution') == 'True': continue break except (KeyboardInterrupt, SystemExit) as e: pass except PyCoQuitException as e: disp('Exiting...') infinite_loop = False break except Exception as e: disp('Exception "{0}": {1}'.format(cmd_class.__cmd_name__, e), color='red') else: disp('Command "{0}" not found.'.format( command_str.split(' ')[0])) if suggested_cmd is not None: disp('Did you mean: "{0}"?'.format(suggested_cmd), color='red') return 0
def impl(self): if self.get_options().delete: Hist.get_instance().delete() disp('History deleted.') return 0 try: lines = Hist.get_instance().read() search = self.get_options().search if search: disp('Searching for: "{0}"'.format(' '.join(search))) unique_lines = defaultdict(float) for line in lines: if line not in unique_lines and not line.startswith('history'): score = 0.0 for part in search: if part in line: score += 1.0 unique_lines[line] = score / float(max(len(line.split(' ')), len(search))) del lines # free some memory top_lines = sorted(unique_lines.items(), key=itemgetter(1), reverse=True)[:5] if not top_lines: disp('Not found...') return 0 for line, score in top_lines: disp('{0:.2f}\t{1}'.format(score, line)) disp('...') else: for line in lines: disp(line) except Exception as e: disp('Exception: {0}'.format(sys.exc_info()[0]), color='red') return 1 return 0
def impl(self): disp(self.HELP) return 0
def impl(self): disp(' '.join(self.get_options().echo)) return 0
def main(): command_resolver = CommandResolver.get_instance() history = History.get_instance() disp('Loading config...') try: ConfigLoader('.config') except Exception as e: disp('ConfigLoader: {0}'.format(e), color='red') disp('Loading aliases...') try: AliasLoader() except Exception as e: disp('AliasLoader: {0}'.format(e), color='red') infinite_loop = True while infinite_loop: disp(Prompt().show(), color='blue', end='') command_str = get_input().strip() if not command_str: continue history.append(command_str) command_pipe = command_resolver.resolve(command_str) for cmd_class, options, suggested_cmd in command_pipe: disp('cmd_class: {0} options: {1} suggested_cmd: {2}'.format(cmd_class, options, suggested_cmd), debug=True) if cmd_class is not None: try: # if the PycoStringBuffer is not empty means that | or || # has been used if PycoStringBuffer.get() and len(command_pipe) > 1: options.append(PycoStringBuffer.get()) r = cmd_class(options).run() if r != 0: disp('Command "{0}" finished with exit code: {1}'.format(cmd_class.__cmd_name__, r), color='red') # see parser '&' definition if _GV_.get('pyco_unconditional_execution') == 'True': continue break except (KeyboardInterrupt, SystemExit) as e: pass except PyCoQuitException as e: disp('Exiting...') infinite_loop = False break except Exception as e: disp('Exception "{0}": {1}'.format(cmd_class.__cmd_name__, e), color='red') else: disp('Command "{0}" not found.'.format(command_str.split(' ')[0])) if suggested_cmd is not None: disp('Did you mean: "{0}"?'.format(suggested_cmd), color='red') return 0
def impl(self): if not self.get_options().values: return 1 def get_values(values): res = [] for v in values: for num in v.split(','): num = num.strip() if num: res.append(num) return res values = get_values(self.get_options().values) for v in values: try: values.append(float(v)) except Exception as e: disp('Value: "{0}" is not a valid number'.format(v), color='red') # TODO sooner or later we will add numpy (if we found a painless way of adding it) if self.get_options().mean: disp('{0}'.format(mean(values))) return 0 if self.get_options().var: disp('{0}'.format(variance(values))) return 0 if self.get_options().std: disp('{0}'.format(sqrt(variance(values)))) return 0 disp('m: {0}'.format(mean(values))) disp('v: {0}'.format(variance(values))) disp('s: {0}'.format(sqrt(variance(values)))) return 0
def impl(self): disp(os.getcwd()) return 0
def add(command_name, command_class, command_options): if command_name in CommandResolver._command_map: disp('Command "{0}" has been overridden by class "{1}"'.format(command_name, command_class.__name__), color='red') CommandResolver._command_map[command_name] = (command_class, command_options)
def impl(self): disp(os.getcwd()) return 0
def __init__(self, config_file_path): super(ConfigLoader, self).__init__(config_file_path) for key, value in self.load(): disp('{0} = {1}'.format(key, value)) GlobalVariables.get_instance().set(key, value)
def impl(self): disp(self.HELP) return 0
def impl(self): disp(' '.join(self.get_options().echo)) return 0
def __init__(self, config_file_path): super(ConfigLoader, self).__init__(config_file_path) for key, value in self.load(): disp('{0} = {1}'.format(key, value)) GlobalVariables.get_instance().set(key, value)
def impl(self): if not self.get_options().values: return 1 def get_values(values): res = [] for v in values: for num in v.split(','): num = num.strip() if num: res.append(num) return res values = get_values(self.get_options().values) for v in values: try: values.append(float(v)) except Exception as e: disp('Value: "{0}" is not a valid number'.format(v), color='red') # TODO sooner or later we will add numpy (if we found a painless way of adding it) if self.get_options().mean: disp('{0}'.format(mean(values))) return 0 if self.get_options().var: disp('{0}'.format(variance(values))) return 0 if self.get_options().std: disp('{0}'.format(sqrt(variance(values)))) return 0 disp('m: {0}'.format(mean(values))) disp('v: {0}'.format(variance(values))) disp('s: {0}'.format(sqrt(variance(values)))) return 0
def impl(self): if self.get_options().delete: Hist.get_instance().delete() disp('History deleted.') return 0 try: lines = Hist.get_instance().read() search = self.get_options().search if search: disp('Searching for: "{0}"'.format(' '.join(search))) unique_lines = defaultdict(float) for line in lines: if line not in unique_lines and not line.startswith( 'history'): score = 0.0 for part in search: if part in line: score += 1.0 unique_lines[line] = score / float( max(len(line.split(' ')), len(search))) del lines # free some memory top_lines = sorted(unique_lines.items(), key=itemgetter(1), reverse=True)[:5] if not top_lines: disp('Not found...') return 0 for line, score in top_lines: disp('{0:.2f}\t{1}'.format(score, line)) disp('...') else: for line in lines: disp(line) except Exception as e: disp('Exception: {0}'.format(sys.exc_info()[0]), color='red') return 1 return 0
def run(self): disp('{0} {1}'.format(self.name, self.get_options()), debug=True) if self.get_options().version: disp('{0} {1}'.format(self.name, self.version)) return 1 return self.impl()
""" author = 'Pierluigi' date = '2016-05-13' """ from __future__ import print_function import codecs import platform import sys from colorama import init from pyco.utils import disp from pyco.version import __version__ as pyco_ver disp('PyCo {0}'.format(pyco_ver)) disp('System: {0} {1}'.format(platform.system(), platform.release())) sys.stdout = codecs.getwriter('utf8')(sys.stdout) sys.stderr = codecs.getwriter('utf8')(sys.stderr) disp('stdout and stderr: utf8') get_input = raw_input if sys.version_info[0] >= 3: get_input = input disp('input redirected: done') disp('is tty: {0}'.format(sys.stdout.isatty())) init(autoreset=True)