def test_install(): console = Console(file=io.StringIO()) dh = sys.displayhook install(console) sys.displayhook("foo") assert console.file.getvalue() == "'foo'\n" assert sys.displayhook is not dh
def main(self): pretty.install() install() shell = AutoShell() self.init(shell) out_list = [] if self.all_flag: for PM in self.PMs: pm = PM() out_list.extend(pm.get_all_packages()) else: for package_name in self.known_packages.keys(): try: package = UniversalePackage( package_name, shell=shell, pms_classes=self.PMs, # не работает как надо! known_packages=self.known_packages, ) except PackageManagerNotInatalled: continue if package.is_installed(): ver = package.info.get("version", None) if not ver: out_list.append(f"{package_name}") else: out_list.append(f"{package_name}@{ver}") for line in out_list: print(line) if self.output != None: data = {"packages": out_list} with open(self.output, 'w+') as f: yaml.dump(data, f, default_flow_style=False)
def ReplInit(): # # Install the pretty printer that rich provides to replace the existing # printer. # pretty.install(indent_guides=True, expand_all=True) console = Console() console.rule('Matter REPL') console.print(''' [bold blue] Welcome to the Matter Python REPL! For help, please type [/][bold green]matterhelp()[/][bold blue] To get more information on a particular object/class, you can pass that into [bold green]matterhelp()[/][bold blue] as well. ''') console.rule() coloredlogs.install(level='DEBUG') chip.logging.RedirectToPythonLogging() # logging.getLogger().setLevel(logging.DEBUG) logging.getLogger().setLevel(logging.WARN)
def load_ipython_extension(ip: Any) -> None: # pragma: no cover # prevent circular import from rich.pretty import install from rich.traceback import install as tr_install install() tr_install()
def __init__(self, dataStructure): super(interactiveDataStructures, self).__init__() # rich module elements pretty.install() traceback.install() self.console = Console() # Datastructure elements availableDataStrutuces = { 'DynamicArray': DynamicArray(), 'SingleLinkedList': SinglyLinkedList(), 'DoublyLinkedList': DoublyLinkedList(), 'Stack': Stack(), 'Queue': Queue(), 'PriorityQueue': PriorityQueue() } correspondingNodes = { 'DynamicArray': None, 'SingleLinkedList': ListNode(None), 'DoublyLinkedList': ListNode(None), 'Stack': StackNode(None), 'Queue': QueueNode(None), 'PriorityQueue': PQNode(None) } if dataStructure in availableDataStrutuces: self.dataStructure = availableDataStrutuces[dataStructure] self.DSNode = correspondingNodes[dataStructure] self.DSname = dataStructure interactiveDataStructures.prompt = text.Text(f'({dataStructure}) ', style="bold magenta") # doesn't quite work else: raise ValueError(f'Please choose one of the following available data structure: {availableDataStrutuces.keys()}')
def __init__(self): pretty.install() self.c = Console() self.bot_print(__FIGLET__, figlet=True) self.bot_print('Checking chromedriver version...') chromedriver_autoinstaller.install(cwd=True) config = configparser.ConfigParser() config.read('config.txt') self.automatic = config.getboolean('leadmonster', 'auto_mode') self.max_leads_per_company = config.getint('leadmonster', 'max_leads_per_company') self.max_random_delay = config.getint('leadmonster', 'max_random_delay') self.search = '' self.keywords = [] self.location = '' self.max_company_size = 9999999 self.scraped_postings = [] self.lead_list = [] self.output = [] self.job_count = 0 self.date_filter = None self.email_generator = EmailGenerator() with open('blacklist.txt') as f: self.blacklist = self.lowercase_set( [i.strip().lower() for i in f.readlines() if i.strip()]) with open('posting_history.json') as f: self.posting_history = json.loads(f.read()) # Create folders if not os.path.exists('data'): os.mkdir('./data')
def main(self, package_name: str): pretty.install() install() shell = AutoShell() self.init(shell) package = UniversalePackage( package_name, shell=shell, pms_classes=self.PMs, auto_update_conf=not self.no_auto_update_conf) package.install()
def main(): pretty.install() ap = argparse.ArgumentParser() ap.add_argument('-p', '--pages', type=check_positive, required=False, default=2, help='number of page results to display [default=2]') ap.add_argument('query', nargs='+', type=str, help='terms to search pypi.org package repository') args = ap.parse_args() search(query=' '.join(args.query), pages=args.pages)
def main(self, package_name: str): pretty.install() install() shell = AutoShell() self.init(shell) data = {} for pm in self.PMs: try: out = pm(shell=shell).search(package_name) if out != {}: data[pm.name] = out except NotImplementedError as e: logger.warning( f"{pm.name} not have search method!") # , exc_info=True) if self.list_mode: print_search_results(data) else: print_info(data)
def init_console(style="dark", theme="brunante", color_system="auto", force_jupyter=None): def _patch_heading(self, *_args): """By default, all headings are centered by Rich; I prefer to have them left-justified, except for <h3> """ text = self.text text.justify = "left" if self.level == 3: yield Text(" ") + text else: yield text Heading.__rich_console__ = _patch_heading def _patch_code_block(self, *_args): code = str(self.text).rstrip() if self.lexer_name == "default": self.lexer_name = "python" syntax = Syntax(code, self.lexer_name, theme=theme, word_wrap=True) yield syntax CodeBlock.__rich_console__ = _patch_code_block if style == "light": console = Console( theme=light_background_theme, color_system=color_system, # noqa force_jupyter=force_jupyter, ) else: console = Console( theme=dark_background_theme, color_system=color_system, # noqa force_jupyter=force_jupyter, ) pretty.install(console=console, indent_guides=True) return console
def main(self, package_name): pretty.install() install() shell = AutoShell() self.init(shell) logger.debug( f"Args:\n\tpackage_name = {package_name},\n\tpm_names = {self.pm_names}\n\tall = {self.all_flag}\n\toffline = {self.offline}" ) package = UniversalePackage(package_name, shell=shell, pms_classes=self.PMs, known_packages=self.known_packages) package.update_package_info(all_pm=self.all_flag) info = package.info if info == {}: logger.error("Package Does Not Found") return print_info(info) if package_name not in self.known_packages: update_user_known_package(package_name, package.config)
def __init__(self, rendezvousAddr=None, controllerNodeId=1, bluetoothAdapter=None): self.lastNetworkId = None self.replHint = None pretty.install(indent_guides=True, expand_all=True) coloredlogs.install(level='DEBUG') chip.logging.RedirectToPythonLogging() logging.getLogger().setLevel(logging.DEBUG) warnings.showwarning = ShowColoredWarnings Cmd.__init__(self) Cmd.identchars = string.ascii_letters + string.digits + "-" if sys.stdin.isatty(): self.prompt = "chip-device-ctrl > " else: self.use_rawinput = 0 self.prompt = "" DeviceMgrCmd.command_names.sort() self.bleMgr = None self.chipStack = ChipStack.ChipStack( bluetoothAdapter=bluetoothAdapter, persistentStoragePath='/tmp/chip-device-ctrl-storage.json') self.fabricAdmin = FabricAdmin.FabricAdmin(0xFFF1) self.devCtrl = self.fabricAdmin.NewController(nodeId=controllerNodeId, useTestCommissioner=True) self.commissionableNodeCtrl = ChipCommissionableNodeCtrl.ChipCommissionableNodeController( self.chipStack) # If we are on Linux and user selects non-default bluetooth adapter. if sys.platform.startswith("linux") and (bluetoothAdapter is not None): try: self.bleMgr = BleManager(self.devCtrl) self.bleMgr.ble_adapter_select( "hci{}".format(bluetoothAdapter)) except Exception as ex: traceback.print_exc() print( "Failed to initialize BLE, if you don't have BLE, run chip-device-ctrl with --no-ble" ) raise ex self.historyFileName = os.path.expanduser( "~/.chip-device-ctrl-history") try: import readline if "libedit" in readline.__doc__: readline.parse_and_bind("bind ^I rl_complete") readline.set_completer_delims(" ") try: readline.read_history_file(self.historyFileName) except IOError: pass except ImportError: pass
from pyinspect.builtins import List, Tuple, Dict, pilist, pidict from pyinspect._colors import ( salmon, lightsalmon, orange, mocassin, lightblue, lightorange, gray, ) from rich import pretty pretty.install( overflow="ellipse", max_length=33, ) try: from github import Github except Exception: Github = None __author__ = "Federico Claudi" __license__ = "MIT" __maintainer__ = "Federico Claudi" __email__ = "*****@*****.**" __status__ = "dev" __website__ = "https://github.com/FedeClaudi/pyinspect" __version__ = "0.0.9"
def init_console(theme="dark"): if not rich_available: return None def _patch_heading(self, console, options): """By default, all headings are centered by Rich; I prefer to have them left-justified, except for <h3> """ text = self.text text.justify = "left" if self.level == 3: yield Text(" ") + text else: yield text Heading.__rich_console__ = _patch_heading def _patch_code_block(self, console, options): code = str(self.text).rstrip() if self.lexer_name == "default": self.lexer_name = "python" if theme == "light": syntax = Syntax(code, self.lexer_name, theme="tango") else: syntax = Syntax(code, self.lexer_name, theme="brunante") yield syntax CodeBlock.__rich_console__ = _patch_code_block _theme = { "markdown.h1": "bold #B22518", "markdown.h2": "bold #009999 underline", # Exception message; location header "markdown.h3": "bold #CF6A4C", # likely cause "markdown.h4": "bold #CF6A4C", # warning header "markdown.link": "bold #DAEFA3 underline", "markdown.code": "#CDA869", } if brunante is not None: _theme.update(**brunante.my_style) dark_background_theme = Theme(_theme) light_background_theme = Theme({ "markdown.h1": "bold #B22518", "markdown.h2": "bold #B22518 underline", # Exception message; location header "markdown.h3": "bold #0000cf", # likely cause "markdown.h4": "bold #CF6A4C", # warning header "markdown.link": "bold #3465a4 underline", "markdown.item.bullet": "#3465a4", "markdown.code": "#0000cf", }) if theme == "light": console = Console(theme=light_background_theme) else: console = Console(theme=dark_background_theme) # Rich has no version attribute that we can check try: # indent_guide need Rich version 9.1+ pretty.install(console=console, indent_guides=True) except Exception: pretty.install(console=console) return console
# -*- coding: utf-8 -*- ######################################################################## # # # # # # # MIT License # # Copyright (c) 2021 Michael Nikitenko # # # ######################################################################## from rich import pretty pretty.install() # Beautifuliser for python syntax and etc ONLY IN REPL MODE! if __name__ == '__main__': print('["Rich and pretty", True]') print(locals())
def repl(ctx, cli_obj, db, emacs, beta, **kwargs): """Run interactive osxphotos REPL shell (useful for debugging, prototyping, and inspecting your Photos library)""" import logging from objexplore import explore from photoscript import Album, Photo, PhotosLibrary from rich import inspect as _inspect from osxphotos import ExifTool, PhotoInfo, PhotosDB from osxphotos.albuminfo import AlbumInfo from osxphotos.momentinfo import MomentInfo from osxphotos.photoexporter import ExportOptions, ExportResults, PhotoExporter from osxphotos.placeinfo import PlaceInfo from osxphotos.queryoptions import QueryOptions from osxphotos.scoreinfo import ScoreInfo from osxphotos.searchinfo import SearchInfo logger = logging.getLogger() logger.disabled = True pretty.install() print(f"python version: {sys.version}") print(f"osxphotos version: {osxphotos._version.__version__}") db = db or get_photos_db() photosdb = _load_photos_db(db) # enable beta features if requested if beta: photosdb._beta = beta print("Beta mode enabled") print("Getting photos") tic = time.perf_counter() try: query_options = _query_options_from_kwargs(**kwargs) except IncompatibleQueryOptions: click.echo("Incompatible query options", err=True) click.echo(ctx.obj.group.commands["repl"].get_help(ctx), err=True) sys.exit(1) photos = _query_photos(photosdb, query_options) all_photos = _get_all_photos(photosdb) toc = time.perf_counter() tictoc = toc - tic # shortcut for helper functions get_photo = photosdb.get_photo show = _show_photo spotlight = _spotlight_photo get_selected = _get_selected(photosdb) try: selected = get_selected() except Exception: # get_selected sometimes fails selected = [] def inspect(obj): """inspect object""" return _inspect(obj, methods=True) print(f"Found {len(photos)} photos in {tictoc:0.2f} seconds\n") print("The following classes have been imported from osxphotos:") print( "- AlbumInfo, ExifTool, PhotoInfo, PhotoExporter, ExportOptions, ExportResults, PhotosDB, PlaceInfo, QueryOptions, MomentInfo, ScoreInfo, SearchInfo\n" ) print("The following variables are defined:") print(f"- photosdb: PhotosDB() instance for {photosdb.library_path}") print( f"- photos: list of PhotoInfo objects for all photos filtered with any query options passed on command line (len={len(photos)})" ) print( f"- all_photos: list of PhotoInfo objects for all photos in photosdb, including those in the trash (len={len(all_photos)})" ) print( f"- selected: list of PhotoInfo objects for any photos selected in Photos (len={len(selected)})" ) print(f"\nThe following functions may be helpful:") print( f"- get_photo(uuid): return a PhotoInfo object for photo with uuid; e.g. get_photo('B13F4485-94E0-41CD-AF71-913095D62E31')" ) print( f"- get_selected(); return list of PhotoInfo objects for photos selected in Photos" ) print( f"- show(photo): open a photo object in the default viewer; e.g. show(selected[0])" ) print( f"- show(path): open a file at path in the default viewer; e.g. show('/path/to/photo.jpg')" ) print(f"- spotlight(photo): open a photo and spotlight it in Photos") # print( # f"- help(object): print help text including list of methods for object; for example, help(PhotosDB)" # ) print( f"- inspect(object): print information about an object; e.g. inspect(PhotoInfo)" ) print( f"- explore(object): interactively explore an object with objexplore; e.g. explore(PhotoInfo)" ) print(f"- q, quit, quit(), exit, exit(): exit this interactive shell\n") embed_repl( globals=globals(), locals=locals(), history_filename=str(pathlib.Path.home() / ".osxphotos_repl_history"), quit_words=["q", "quit", "exit"], vi_mode=not emacs, )
os_name = str(platform.system()).lower() if os_name == windows_os: clointfusion_directory = r"C:\Users\{}\ClointFusion".format( str(os.getlogin())) elif os_name == linux_os: clointfusion_directory = r"/home/{}/ClointFusion".format(str( os.getlogin())) elif os_name == mac_os: clointfusion_directory = r"/Users/{}/ClointFusion".format( str(os.getlogin())) cf_icon_cdt_file_path = os.path.join(clointfusion_directory, "Logo_Icons", "Cloint-ICON-CDT.ico") pi.install_traceback(hide_locals=True, relevant_only=True, enable_prompt=True) pretty.install() toaster = ToastNotifier() local_msg = "" local_url = "" local_date = datetime.datetime.now().strftime("%d/%m/%Y") server_date = "" def act_on_click(): global local_msg if "new version" in str(local_msg).lower():\ os.system('cf') else:
def better_debug(cls): install() pretty.install()