我们从Python开源项目中,提取了以下13个代码示例,用于说明如何使用sublime.decode_value()。
def getJsonOrGenerate(name, callback): filename = getI18nCachePath() + name + '.json' if os.path.exists(filename): with open(filename, 'r', encoding='utf8') as f: json = f.read(10485760) content = sublime.decode_value(json) else: content = callback() dirname = os.path.dirname(filename) if not os.path.isdir(dirname): os.makedirs(dirname) with open(filename, 'w', encoding="utf8") as f: f.write(sublime.encode_value(content)) return content
def load_folder_settings_file(folder_settings_file): try: folder_settings_file = open(folder_settings_file, "r") except IOError as e: sublime.error_message("Error: spandoc.json exists, but could not be read. Exception: " + str(e)) folder_settings_file.close() else: settings_file_commented = folder_settings_file.read() folder_settings_file.close() # debug("settings_file_commented: " + str(settings_file_commented)) try: settings_file = sublime.decode_value(settings_file_commented) except (KeyError, ValueError) as e: sublime.error_message("JSON Error: Cannot parse spandoc.json. See console for details. Exception: " + str(e)) return None # debug("settings_file: " + str(settings_file)) return settings_file
def process_message(self) -> None: """Called when a full line has been read from the socket """ message = b''.join(self.rbuffer) self.rbuffer = [] try: data = sublime.decode_value(message.decode('utf8')) except (NameError, ValueError): data = json.loads(message.replace(b'\t', b' ' * 8).decode('utf8')) callback = self.pop_callback(data.pop('uid')) if callback is None: logger.error( 'Received {} from the JSONServer but there is not callback ' 'to handle it. Aborting....'.format(message) ) try: callback(data) except Exception as error: logging.error(error) for traceback_line in traceback.format_exc().splitlines(): logging.error(traceback_line)
def run(self, args, simulate=False): view = self.view window = view.window() save_and_format(window) if not check_num_selections(view, 1): return byte_offset = view.sel()[0].begin() cmd = [ 'guru', '-json', 'describe', view.file_name() + ':#' + str(byte_offset) ] cmd_output = run_tool(cmd) if not cmd_output: return json_obj = sublime.decode_value(cmd_output.decode('utf-8')) type_str = json_obj['value']['type'] window.settings().set(SettingsKeys.PANEL_QUERIED_TYPE, type_str) window.run_command('show_go_doc_from_panel') window.settings().erase(SettingsKeys.PANEL_QUERIED_TYPE)
def main(): try: with open(file) as fp: obj = sublime.decode_value(fp.read()) except FileNotFoundError: return keys = {} def add_keys(obj, keys): if isinstance(obj, list): for item in obj: add_keys(item, keys) elif isinstance(obj, dict): for key, item in obj.items(): keys[key] = type(item).__name__ add_keys(item, keys) if key != 'args' else None return keys add_keys(obj, keys)
def getAllLanguages(): return sublime.decode_value(sublime.load_resource('Packages/' + package_name + '/languages.json'))
def decodeEntity(xml, category='iso'): global entities if not isinstance(xml, str): return xml if entities[category]: forward, reverse = entities[category] else: resourceMap = { "iso": "IsoEntities.json", "html": "HtmlEntities.json", } forward = sublime.decode_value(sublime.load_resource('Packages/' + package_name + '/' + resourceMap[category])) reverse = dict((v, k) for k, v in forward.items()) entities[category] = (forward, reverse) def parseEntity(match): entity = match.group(1) try: if entity.isdigit(): return reverse[int(entity)] else: return chr(forward[entity]) except: return match.group(0) xml = re.sub('&([a-zA-Z0-9]+);', parseEntity, xml) return xml
def get_stylesheets(self): """Get the stylesheet dict from the file or return an empty dictionary no file contents.""" if not len(self.style_sheets): content = self.load_stylesheets_content() if len(content): self.style_sheets = sublime.decode_value(str(content)) return self.style_sheets
def on_load_async(self, view): if view and view.file_name() and not view.settings().get('open_with_edit'): item = SideBarItem(os.path.join(sublime.packages_path(), 'User', 'SideBarEnhancements', 'Open With', 'Side Bar.sublime-menu'), False) if item.exists(): settings = sublime.decode_value(item.contentUTF8()) selection = SideBarSelection([view.file_name()]) for item in settings[0]['children']: try: if item['open_automatically'] and selection.hasFilesWithExtension(item['args']['extensions']): SideBarFilesOpenWithCommand(sublime_plugin.WindowCommand).run([view.file_name()], item['args']['application'], item['args']['extensions']) view.window().run_command('close') break except: pass
def tweak_theme(): view = sublime.active_window().active_view() theme = view.settings().get('theme') if theme is None: print("Can't guess current theme.") return theme_path = os.path.join(sublime.packages_path(), 'User', theme) if os.path.exists(theme_path): with open(theme_path, mode='r', encoding='utf-8') as f: theme_text = f.read() if PYTEST_MARKERS.search(theme_text): print("Already patched") return safety_path = os.path.join( sublime.packages_path(), 'User', 'Original-' + theme) with open(safety_path, mode='w', encoding='utf-8') as f: f.write(theme_text) theme = sublime.decode_value(theme_text) else: theme = [] theme.extend(PYTEST_RULES) tweaked_theme = sublime.encode_value(theme, True) with open(theme_path, mode='w', encoding='utf-8') as f: f.write(tweaked_theme) print('Done tweaking!') # sublime.active_window().open_file(theme_path)
def _parse_tpl(self, cmd): """Parses the builder template """ template_file = os.path.join( os.path.dirname(__file__), '../../', 'templates', 'python_build.tpl' ) with open(template_file, 'r', encoding='utf8') as tplfile: template = Template(tplfile.read()) cmd = cmd.replace('\\', '\\\\') return sublime.decode_value( template.safe_substitute({'python_interpreter': cmd}) )
def _load_index(package, index_file): """ Takes a package name and its associated hyperhelp.json index resource name and loads it. Returns None on failure or a HelpData tuple for the loaded help information on success. """ try: _log("Loading help index for package %s", package) json = sublime.load_resource(index_file) raw_dict = sublime.decode_value(json) except: return _log("Unable to load help index from '%s'", index_file) # Extract all known top level dictionary keys from the help index description = raw_dict.pop("description", "No description available") doc_root = raw_dict.pop("doc_root", None) toc = raw_dict.pop("toc", None) help_files = raw_dict.pop("help_files", dict()) package_files = raw_dict.pop("package_files", dict()) urls = raw_dict.pop("urls", dict()) # Warn about unknown keys still in the dictionary; they are harmless, but # probably the author did something dodgy. for key in raw_dict.keys(): _log("Unknown key '%s' in help index for package '%s'", key, package) if doc_root is None: doc_root = path.split(index_file)[0] else: doc_root = path.normpath("Packages/%s/%s" % (package, doc_root)) # Pull in all the topics. topics = dict() _process_topic_dict(package, topics, help_files) _process_topic_dict(package, topics, package_files) _process_topic_dict(package, topics, urls) if toc is None: toc = [topics.get(topic) for topic in sorted(topics.keys())] else: _validate_toc(package, toc, topics) return HelpData(package, description, index_file, doc_root, topics, sorted(help_files.keys()), sorted(package_files.keys()), list(urls.keys()), toc)