def colorized(response, response_type): """Colorized responses output \nArguments:\n `response` (str) -- Response string\n `response_type` (str) -- Content-type\n \nReturns:\n `None` """ response_formatted = response # Content-types from response headers # todo: # - Add more types to support see supported lexers by pygment if response_type and "application/json" in response_type: jsonified = json.loads(response) formatted_json = json.dumps(jsonified, sort_keys=True, indent=4) response_formatted = highlight(formatted_json, lexers.JsonLexer(), formatters.TerminalFormatter()) if response_type and "text/html" in response_type: response_formatted = highlight(response, lexers.HtmlLexer(), formatters.TerminalFormatter()) return response_formatted
def outputformat(obj, outputformat='txt'): df = pd.DataFrame(obj) if not df.empty: if outputformat == 'csv': click.echo(df.to_csv(index=False)) elif outputformat == 'html': click.echo(df.to_html(index=False)) elif outputformat == 'pretty-html': colorful_html = highlight(df.to_html(index=False), lexers.HtmlLexer(), formatters.TerminalFormatter()) click.echo(colorful_html) elif outputformat == 'json': click.echo(df.to_json(orient='records')) elif outputformat == 'pretty-json': colorful_json = highlight(df.to_json(orient='records'), lexers.JsonLexer(), formatters.TerminalFormatter()) click.echo(colorful_json) elif outputformat == 'latex': click.echo(df.to_latex(index=False)) elif outputformat == 'raw': click.echo(obj) else: # default to txt click.echo(df.to_string(index=False, )) else: click.secho('Warning: no data found', fg='yellow', err=True)
def _get_lexer(codesyntax): if codesyntax in ("cpp", "javascript"): return lexers.JavascriptLexer() elif codesyntax == "python": return lexers.PythonLexer() elif codesyntax == "json": return lexers.JsonLexer() elif codesyntax == "xml" or codesyntax == "html": return lexers.HtmlLexer() elif codesyntax == "yml" or codesyntax == "yaml": return lexers.YamlLexer() elif codesyntax == "css": return lexers.CssLexer() elif codesyntax == "sql": return lexers.SqlLexer() elif codesyntax == "bash" or codesyntax == "sh": return lexers.BashLexer() elif codesyntax == "go": return lexers.GoLexer() elif codesyntax == "diff": return lexers.DiffLexer() elif codesyntax == "emacslisp": return lexers.EmacsLispLexer() elif codesyntax == "lisp": return lexers.CommonLispLexer() elif codesyntax == "rust": return lexers.RustLexer() elif codesyntax == "jsx": return BabylonLexer() elif codesyntax: raise NotImplementedError(codesyntax) else: return lexers.TextLexer()
logger.info("MPD status.") table = [["Descriptions", "Values"], ["http code", r.status_code], ["time spend (sec)", round(t.elapsed_secs, 2)], ["content-length", r.headers['content-length']], ["url", str(r.url)], ["content-type", r.headers['content-type']]] # Output table print tabulate(table, headers="firstrow") # Get Lexer base on content-type if r.headers['content-type'].startswith('application/xml'): lexer = lexers.XmlLexer() elif r.headers['content-type'].startswith('application/json'): lexer = lexers.JsonLexer() else: lexer = lexers.HtmlLexer() # Try to print JSON content try: # Format Json with indentation formatted_http_response = json.dumps(json.loads(r.text), sort_keys=True, indent=2) except Exception: formatted_http_response = r.text print("content:\n{}".format(highlight(formatted_http_response,lexer, formatters.TerminalFormatter()))) except ValueError as e: logger.critical("Json file invalid: {}".format(e)) except KeyError as e: print e logger.critical("MPD configuration do not exist for {}.".format(user_params.m))
class EditorScreen(Screen): row_num = ObjectProperty(None) col_num = ObjectProperty(None) text_input_area = ObjectProperty(None) file_name_input = ObjectProperty(None) language_mode_chooser = ObjectProperty(None) dashboard = ObjectProperty(None) toggle_btn_file_chooser = ObjectProperty(None) lexer_dict = DictProperty({ "Plain text": lexers.get_lexer_by_name("text"), "C": lexers.CLexer(), "C++": lexers.CppLexer(), "CSS": lexers.CssLexer(), "HTML": lexers.HtmlLexer(), "JavaScript": lexers.JavascriptLexer(), "Kivy": KivyLexer(), "Rust": lexers.RustLexer(), "Python": lexers.PythonLexer(), "Python3": lexers.Python3Lexer(), "SASS": lexers.SassLexer(), "SCSS": lexers.ScssLexer(), }) def __init__(self, **kwargs): super().__init__(**kwargs) self.set_syntax_highlight(tuple(self.lexer_dict.keys())[0]) self.text_input_area.bind(cursor=self.on_cursor) self.language_mode_chooser.bind(text=self.on_lang_mode_chooser) self.file_path = "" self.progress_popup = None self.gen_to_progress = None def on_cursor(self, instance, cursor): # cursor[0]: current cursor postition(col) # cursor[1]: current cursor postition(row) self.col_num.text = str(cursor[0]) self.row_num.text = str(cursor[1] + 1) def on_lang_mode_chooser(self, instance, text): self.set_syntax_highlight(text) def set_syntax_highlight(self, language): self.text_input_area.lexer = self.lexer_dict[language] def toggle_file_chooser_show(self): if self.toggle_btn_file_chooser.state == "normal": # self.dashboard_file_chooser = None self.dashboard.clear_widgets() self.dashboard.size_hint_x = None self.dashboard.width = 0 elif self.toggle_btn_file_chooser.state == "down": self.dashboard.add_widget( DashBoardFileChooserView(file_chooser_user=self)) self.dashboard.size_hint_x = 0.4 def clear_text(self): self.text_input_area.text = "" def save_file(self, file_path): with open(file_path, "w") as f: f.write(self.text_input_area.text) self.file_path = file_path return True def show_save(self): def close(): if self.toggle_btn_file_chooser.state == "down": self.toggle_btn_file_chooser.state = "normal" self.toggle_file_chooser_show() # self.toggle_btn_file_chooser.state = "down" # self.toggle_file_chooser_show() popup = SaveFilePopup(self.save_file, close) popup.open() def open_file_yield_progress(self, file_path, *args): progress_max = 0 progress_count = 0 try: with open(file_path, "r") as f: progress_max = sum(1 for line in open(file_path, "r")) + 1 yield progress_count, progress_max text = "" for line in f: text += line progress_count += 1 yield progress_count, progress_max self.text_input_area.text = text self.file_name_input.text = Path(file_path).parts[-1] self.file_path = file_path progress_count += 1 yield progress_count, progress_max except PermissionError: self.text_input_area.text = (":( Permisson denined: {}".format( Path(file_path).parts[-1])) yield progress_max, progress_max except UnicodeDecodeError: self.text_input_area.text = (":( Unicode decode error: {}".format( Path(file_path).parts[-1])) yield progress_max, progress_max def open_file(self, file_path): try: with open(file_path, "r") as f: text = "" for line in f: text += line self.text_input_area.text = text self.file_name_input.text = Path(file_path).parts[-1] self.file_path = file_path except PermissionError: self.text_input_area.text = (":( Permisson denined: {}".format( Path(file_path).parts[-1])) except UnicodeDecodeError: self.text_input_area.text = (":( Unicode decode error: {}".format( Path(file_path).parts[-1])) else: return True def update_progress_popup(self, dt): try: value, max_value = next(self.gen_to_progress) self.progress_popup.set_progress_max(max_value) self.progress_popup.set_progress_value(value) # --- This code For speeding up to opening file. if dt == 0: dt = -1 else: dt = 0 # --- Clock.schedule_once(self.update_progress_popup, dt) except StopIteration: Clock.unschedule(self.show_progress_schedule) self.progress_popup.dismiss() def open_file_with_progress(self, file_path): self.progress_popup = ProgressPopup() self.gen_to_progress = self.open_file_yield_progress(file_path) self.show_progress_schedule = Clock.schedule_interval( self.update_progress_popup, 0) def show_open(self): open_file_popup = OpenFilePopup(self.open_file_with_progress) open_file_popup.open() def show_license(self): save_file_popup = LicensePopup() save_file_popup.open()