我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用sublime.platform()。
def run(self): info = {} info['platform'] = sublime.platform() info['version'] = sublime.version() info['file_icons_version'] = __version__ info['pc_install'] = is_installed_by_package_control() info['current_theme'] = get_current_theme() info['installed_themes'] = get_installed_themes() msg = textwrap.dedent( '''\ - File Icons: %(file_icons_version)s - Sublime Text: %(version)s - Platform: %(platform)s - Package Control: %(pc_install)s - Current Theme: %(current_theme)s - Installed Themes: %(installed_themes)s ''' % info ) sublime.message_dialog( msg + '\nInfo has been copied to the clipboard.' ) sublime.set_clipboard(msg)
def find_ancestor_cmd_path(self, cmd, cwd): """Recursively check for command binary in ancestors' node_modules/.bin directories.""" node_modules_bin = path.normpath(path.join(cwd, 'node_modules/.bin/')) binary = path.join(node_modules_bin, cmd) if sublime.platform() == 'windows' and path.splitext(binary)[1] != '.cmd': binary += '.cmd' if binary and access(binary, X_OK): return binary parent = path.normpath(path.join(cwd, '../')) if parent == '/' or parent == cwd: return None return self.find_ancestor_cmd_path(cmd, parent)
def packages_relative_path(path, prefix_packages=True): """ Return a Packages-relative version of path with '/' as the path separator. Sublime Text wants Packages-relative paths used in settings and in the plugin API to use '/' as the path separator on all platforms. This method converts platform path separators to '/'. If insert_packages = True, 'Packages' is prefixed to the converted path. """ components = get_path_components(path) if prefix_packages and components and components[0] != 'Packages': components.insert(0, 'Packages') return '/'.join(components)
def find_python_script(python_path, script): """Return the path to the given script, or None if not found.""" if sublime.platform() in ('osx', 'linux'): pyenv = which('pyenv') if pyenv: out = run_shell_cmd((os.environ['SHELL'], '-l', '-c', 'echo ""; {} which {}'.format(pyenv, script))).strip().decode().split('\n')[-1] if os.path.isfile(out): return out return which(script) else: # On Windows, scripts may be .exe files or .py files in <python directory>/Scripts scripts_path = os.path.join(os.path.dirname(python_path), 'Scripts') script_path = os.path.join(scripts_path, script + '.exe') if os.path.exists(script_path): return script_path script_path = os.path.join(scripts_path, script + '-script.py') if os.path.exists(script_path): return script_path return None
def get_font_scale(self): """Get font scale.""" scale = 1.0 try: pref_scale = float(sublime.load_settings('Preferences.sublime-settings').get('mdpopups.font_scale', 0.0)) except Exception: pref_scale = 0.0 if sublime.platform() == 'windows' and pref_scale <= 0.0: try: import ctypes logpixelsy = 90 dc = ctypes.windll.user32.GetDC(0) height = ctypes.windll.gdi32.GetDeviceCaps(dc, logpixelsy) scale = float(height) / 96.0 ctypes.windll.user32.ReleaseDC(0, dc) except Exception: pass elif pref_scale > 0.0: scale = pref_scale return scale
def run(self): if sublime.platform() == "linux": preset_path = "/usr/share/%s/" % APP_NAME.lower() elif sublime.platform() == "windows": preset_path = "C:/%s/" % APP_NAME.lower() elif platform.system() == "Darwin": preset_path = os.path.join(os.path.expanduser("~"), "Applications", "%s.app" % APP_NAME, "Contents", "Resources", APP_NAME) else: preset_path = "" self.window.show_input_panel("Set Kodi folder", preset_path, self.set_kodi_folder, None, None)
def run(self, edit, encoding, file_name, need_codecs): self.view.set_name('ConvertToUTF8 Instructions') self.view.set_scratch(True) self.view.settings().set("word_wrap", True) msg = 'File: {0}\nEncoding: {1}\nError: '.format(file_name, encoding) if need_codecs: msg = msg + 'Codecs missing\n\n' branch = self.get_branch(sublime.platform(), sublime.arch()) if branch: ver = '33' if ST3 else '26' msg = msg + 'Please install Codecs{0} plugin (https://github.com/seanliang/Codecs{0}/tree/{1}).\n'.format(ver, branch) else: import platform msg = msg + 'Please send the following information to sunlxy (at) yahoo.com:\n====== Debug Information ======\nVersion: {0}-{1}\nPlatform: {2}\nPath: {3}\nEncoding: {4}\n'.format( sublime.version(), sublime.arch(), platform.platform(), sys.path, encoding ) else: msg = msg + 'Unsupported encoding, see http://docs.python.org/library/codecs.html#standard-encodings\n\nPlease try other tools such as iconv.\n' self.view.insert(edit, 0, msg) self.view.set_read_only(True) self.view.window().focus_view(self.view)
def run(self, edit): for region in self.view.sel(): line = self.view.line(region) cont = self.view.substr(line) if (len(cont) < 2): pass else: lang = " in " + self.get_syntax() cont = cont.strip() cont = cont + lang p = subprocess.Popen("howdoi " + cont, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) output, errors = p.communicate() # Decode binary data for python 3 output = output.decode('utf-8') # Remove CR for windows. if sublime.platform() == 'windows': output = output.replace('\r', '') self.view.replace(edit, line, output)
def is_hidden(self, filename, path, goto=''): if not (path or goto): # special case for ThisPC return False tests = self.view.settings().get('outline_hidden_files_patterns', ['.*']) if isinstance(tests, str): tests = [tests] if any(fnmatch.fnmatch(filename, pattern) for pattern in tests): return True if sublime.platform() != 'windows': return False # check for attribute on windows: try: attrs = ctypes.windll.kernel32.GetFileAttributesW(join(path, goto, filename)) assert attrs != -1 result = bool(attrs & 2) except (AttributeError, AssertionError): result = False return result
def run(self, paths = [], application = "", extensions = "", args=[]): application_dir, application_name = os.path.split(application) if extensions == '*': extensions = '.*' if extensions == '': items = SideBarSelection(paths).getSelectedItems() else: items = SideBarSelection(paths).getSelectedFilesWithExtension(extensions) import subprocess try: for item in items: if sublime.platform() == 'osx': subprocess.Popen(['open', '-a', application] + args + [item.name()], cwd=item.dirname()) elif sublime.platform() == 'windows': subprocess.Popen([application_name] + args + [escapeCMDWindows(item.path())], cwd=expandVars(application_dir), shell=True) else: subprocess.Popen([application_name] + args + [escapeCMDWindows(item.name())], cwd=item.dirname()) except: sublime.error_message('Unable to "Open With..", probably incorrect path to application.')
def confirm(self, paths, display_paths): import functools window = sublime.active_window() window.show_input_panel("BUG!", '', '', None, None) window.run_command('hide_panel'); yes = [] yes.append('Yes, delete the selected items.'); for item in display_paths: yes.append(item); no = [] no.append('No'); no.append('Cancel the operation.'); while len(no) != len(yes): no.append(''); if sublime.platform() == 'osx': sublime.set_timeout(lambda:window.show_quick_panel([yes, no], functools.partial(self.on_confirm, paths)), 200); else: window.show_quick_panel([yes, no], functools.partial(self.on_confirm, paths))
def confirm(self, paths, display_paths): import functools window = sublime.active_window() window.show_input_panel("BUG!", '', '', None, None) window.run_command('hide_panel'); yes = [] yes.append('Yes, empty the selected items.'); for item in display_paths: yes.append(item); no = [] no.append('No'); no.append('Cancel the operation.'); while len(no) != len(yes): no.append(''); if sublime.platform() == 'osx': sublime.set_timeout(lambda:window.show_quick_panel([yes, no], functools.partial(self.on_confirm, paths)), 200); else: window.show_quick_panel([yes, no], functools.partial(self.on_confirm, paths))
def run(self, paths = []): import subprocess items = [] executable_path = sublime.executable_path() if sublime.platform() == 'osx': app_path = executable_path[:executable_path.rfind(".app/")+5] executable_path = app_path+"Contents/SharedSupport/bin/subl" items.append(executable_path) for item in SideBarSelection(paths).getSelectedItems(): items.append(item.forCwdSystemPath()) items.append(item.path()) subprocess.Popen(items, cwd=items[1])
def get_output(cmd): if int(sublime.version()) < 3000: if sublime.platform() != "windows": # Handle Linux and OS X in Python 2. run = '"' + '" "'.join(cmd) + '"' return commands.getoutput(run) else: # Handle Windows in Python 2. # Prevent console window from showing. startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW return subprocess.Popen(cmd, \ stdout=subprocess.PIPE, \ startupinfo=startupinfo).communicate()[0] else: # Handle all OS in Python 3. run = '"' + '" "'.join(cmd) + '"' return subprocess.check_output(run, stderr=subprocess.STDOUT, shell=True, env=os.environ)
def _status(self, timeout=0.05): """Check the socket status, returns True if it is operable """ check = 'that you can connect to your localhost' addr = '("localhost", {})'.format(self.interpreter.port) if sublime.platform() != 'windows': check = ( 'that the Unix Domain Socket file {} exists and that you can ' 'connect to it' ).format(self.interpreter.host) addr = self.interpreter.host self.tip = ( 'check that there is Python process executing the anaconda ' 'jsonserver.py script running in your system. If there is, check ' '{} writing the following script in your Sublime Text 3 console:' '\n\nimport socket; socket.socket(socket.AF_INET, ' 'socket.SOCK_STREAM).connect({})\n\nIf anaconda works just fine ' 'after you received this error and the command above worked you ' 'can make anaconda to do not show you this error anymore setting ' 'the \'swallow_startup_errors\' to \'true\' in your ' 'configuration file.'.format(check, addr) ) return super(LocalWorker, self)._status(timeout)
def find_executable(executable): """ Return the path to the given executable, or None if not found. create_environment is used to augment PATH before searching for the executable. """ env = create_environment() for base in env.get('PATH', '').split(os.pathsep): path = os.path.join(os.path.expanduser(base), executable) # On Windows, if path does not have an extension, try .exe, .cmd, .bat if sublime.platform() == 'windows' and not os.path.splitext(path)[1]: for extension in ('.exe', '.cmd', '.bat'): path_ext = path + extension if can_exec(path_ext): return path_ext elif can_exec(path): return path return None
def _on_done_select_generator(cls, index): if index == -1: cls._is_selecting = False return cls.generator = cls.items[index][0] platform_support = cls.items[index][1] toolset_support = cls.items[index][2] cls.platform_support = True if "True" in platform_support else False cls.toolset_support = True if "True" in toolset_support else False print("CMakeBuilder: Selected generator is", cls.generator) if cls.platform_support: text = "Platform for {} (Press Enter for default): ".format( cls.generator) print("CMakeBuilder: Presenting input panel for platform.") cls.window.show_input_panel(text, "", cls._on_done_select_platform, None, None) elif cls.toolset_support: cls._select_toolset() else: cls._run_configure_with_new_settings()
def get_output(cmd): if int(sublime.version()) < 3000: if sublime.platform() != "windows": # Handle Linux and OS X in Python 2. run = '"' + '" "'.join(cmd) + '"' return commands.getoutput(run) else: # Handle Windows in Python 2. # Prevent console window from showing. startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW return subprocess.Popen(cmd, \ stdout=subprocess.PIPE, \ startupinfo=startupinfo).communicate()[0] else: # Handle all OS in Python 3. run = '"' + '" "'.join(cmd) + '"' try: return subprocess.check_output(run, stderr=subprocess.STDOUT, shell=True, env=os.environ) except Exception as exception: print(exception.output)
def run(self, edit): def done(path): settings = sublime.load_settings("PICO-8.sublime-settings") settings.set("pico-8_path", path) sublime.save_settings("PICO-8.sublime-settings") return platform = sublime.platform() if platform == "linux": self.view.window().show_input_panel("PICO-8 Path", "/path/to/pico8", done, None, None) elif platform == "osx": self.view.window().show_input_panel("PICO-8 Path", "/path/to/PICO-8.app/Contents/MacOS/pico8", done, None, None) elif platform == "windows": self.view.window().show_input_panel("PICO-8 Path", "C:\\Program Files (x86)\\PICO-8\\pico8.exe", done, None, None) else: sublime.error_message("Error: could not resolve platform\n\n[\"linux\", \"osx\", \"windows\"]") return
def run(self, command_line=''): assert command_line, 'expected non-empty command line' if platform() == 'linux': term = self.view.settings().get('VintageousEx_linux_terminal') term = term or os.environ.get('COLORTERM') or os.environ.get("TERM") if not term: nvim.status_message('not terminal name found') return try: self.open_shell([term, '-e', 'bash']).wait() except Exception as e: nvim.console_message(e) nvim.status_message('error while executing command through shell') return elif platform() == 'osx': term = self.view.settings().get('VintageousEx_osx_terminal') term = term or os.environ.get('COLORTERM') or os.environ.get("TERM") if not term: nvim.status_message('not terminal name found') return try: self.open_shell([term, '-e', 'bash']).wait() except Exception as e: nvim.console_message(e) nvim.status_message('error while executing command through shell') return elif platform() == 'windows': self.open_shell(['cmd.exe', '/k']).wait() else: # XXX OSX (make check explicit) nvim.not_implemented_message('not implemented') # https://vimhelp.appspot.com/insert.txt.html#:r
def get_node_path(): platform = sublime.platform() node = PluginUtils.get_pref("node_path").get(platform) print("Using node.js path on '" + platform + "': " + node) return node # Convert path that possibly contains a user tilde and/or is a relative path into an absolute path.
def get_local_eslint(dirname): pkg = PluginUtils.findup('node_modules/eslint', dirname) if pkg == None: return None else: path = PluginUtils.get_pref("local_eslint_path").get(sublime.platform()) d = os.path.dirname(os.path.dirname(pkg)) esl = os.path.join(d, path) if os.path.isfile(esl): return esl else: return None
def get_eslint_path(dirname): platform = sublime.platform() eslint = PluginUtils.get_local_eslint(dirname) # if local eslint not available, then using the settings config if eslint == None: eslint = PluginUtils.get_pref("eslint_path").get(platform) print("Using eslint path on '" + platform + "': " + eslint) return eslint
def run(self, cmd="/bin/bash -l", title="Terminal", cwd=None, syntax=None, keep_open=False): """ Open a new terminal view Args: cmd (str, optional): Shell to execute. Defaults to 'bash -l. title (str, optional): Terminal view title. Defaults to 'Terminal'. cwd (str, optional): The working dir to start out with. Defaults to either the currently open file, the currently open folder, $HOME, or "/", in that order of precedence. You may pass arbitrary snippet-like variables. syntax (str, optional): Syntax file to use in the view. keep_open (bool, optional): Keep view open after cmd exits. """ if sublime.platform() not in ("linux", "osx"): sublime.error_message("TerminalView: Unsupported OS") return st_vars = self.window.extract_variables() if not cwd: cwd = "${file_path:${folder}}" cwd = sublime.expand_variables(cwd, st_vars) if not cwd: cwd = os.environ.get("HOME", None) if not cwd: # Last resort cwd = "/" args = {"cmd": cmd, "title": title, "cwd": cwd, "syntax": syntax, "keep_open": keep_open} self.window.new_file().run_command("terminal_view_activate", args=args)
def _preexec_val(self): return os.setsid if sublime.platform() != "windows" else None
def kill(self): pid = self.process.pid if sublime.platform() == "windows": kill_process = subprocess.Popen(['taskkill', '/F', '/T', '/PID', str(pid)], stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) kill_process.communicate() else: os.killpg(pid, signal.SIGTERM) ProcessCache.remove(self)
def force_decode(self, text): try: text = text.decode('utf-8') except UnicodeDecodeError: if sublime.platform() == "windows": text = self.decode_windows_line(text) return text
def encode_process_command(self, command): is_sublime_2_and_in_windows = sublime.platform() == "windows" and int(sublime.version()) < 3000 return command.encode(sys.getfilesystemencoding()) if is_sublime_2_and_in_windows else command
def get_subl_executable_path(): """Return the path to the subl command line binary.""" executable_path = sublime.executable_path() if sublime.platform() == 'osx': suffix = '.app/' app_path = executable_path[:executable_path.rfind(suffix) + len(suffix)] executable_path = app_path + 'Contents/SharedSupport/bin/subl' return executable_path # popen utils
def create_tempdir(): """Create a directory within the system temp directory used to create temp files.""" try: if os.path.isdir(tempdir): shutil.rmtree(tempdir) os.mkdir(tempdir) # Make sure the directory can be removed by anyone in case the user # runs ST later as another user. os.chmod(tempdir, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO) except PermissionError: if sublime.platform() != 'windows': current_user = pwd.getpwuid(os.geteuid())[0] temp_uid = os.stat(tempdir).st_uid temp_user = pwd.getpwuid(temp_uid)[0] message = ( 'The SublimeLinter temp directory:\n\n{0}\n\ncould not be cleared ' 'because it is owned by \'{1}\' and you are logged in as \'{2}\'. ' 'Please use sudo to remove the temp directory from a terminal.' ).format(tempdir, temp_user, current_user) else: message = ( 'The SublimeLinter temp directory ({}) could not be reset ' 'because it belongs to a different user.' ).format(tempdir) sublime.error_message(message) from . import persist persist.debug('temp directory:', tempdir)
def get_user_fullname(): """Return the user's full name (or at least first name).""" if sublime.platform() in ('osx', 'linux'): import pwd return pwd.getpwuid(os.getuid()).pw_gecos else: return os.environ.get('USERNAME', 'Me')
def sublime_format_path(pth): """Format path for sublime internal use.""" m = re.match(r"^([A-Za-z]{1}):(?:/|\\)(.*)", pth) if sublime.platform() == "windows" and m is not None: pth = m.group(1) + "/" + m.group(2) return pth.replace("\\", "/")
def visible(self): return platform.system() == "Windows" and self.settings.get("portable_mode")
def pipe_through_prog(cmd, path=None, stdin=''): """Run the Vale binary with the given command. """ startupinfo = None if sublime.platform() == 'windows': startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW p = subprocess.Popen(cmd, cwd=path, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE, startupinfo=startupinfo) out, err = p.communicate(input=stdin.encode('utf-8')) return out.decode('utf-8'), err
def __init__(self): self.default_binary = 'vale' if sublime.platform() == 'windows': self.default_binary += '.exe' self.on_hover = [] self.error_template = None self.warning_template = None self.info_template = None self.css = None self.settings.add_on_change('reload', lambda: self.load()) self.load()
def open_url(url): if sublime.platform() == 'osx': command = 'open' elif sublime.platform() == 'windows': command = 'start' elif sublime.platform() == 'linux': command = 'lynx' command += ' ' + str(url) os.system(command) # ---------------------------------------------------------- # Manager # ----------------------------------------------------------
def is_windows(): return sublime.platform() == 'windows'
def get_branch(self, platform, arch): return [{ 'linux-x64': 'master', 'linux-x32': 'x32', }, { 'linux-x64': 'linux-x64', 'linux-x32': 'linux-x32', 'osx-x64': 'osx', }][ST3].get(platform + '-' + arch)
def response_tab_bindings(): """Returns string with special key bindings for response tab commands. """ replay = '[cmd+r]' if platform == 'osx' else '[ctrl+r]' nav = '[ctrl+alt+ ?/?]' pin = '[cmd+t]' if platform == 'osx' else '[ctrl+t]' save = '[cmd+s]' if platform == 'osx' else '[ctrl+s]' explore = '[cmd+e]' if platform == 'osx' else '[ctrl+e]' return '{} replay request, {} prev/next request, {} pin/unpin tab, {} save request, {} explore URL'.format( replay, nav, pin, save, explore)
def handle_thread(thread, msg=None, counter=0, direction=1, width=8): if thread.is_alive(): next = counter + direction if next > width: direction = -1 elif next < 0: direction = 1 bar = [' '] * (width + 1) bar[counter] = '=' counter += direction status('%s [%s]' % (msg, ''.join(bar))) sublime.set_timeout(lambda: handle_thread(thread, msg, counter, direction, width), 100) else: status(' ok ') # # Code lifted from https://github.com/randy3k/ProjectManager/blob/master/pm.py # def subl(args=[]): # # learnt from SideBarEnhancements # executable_path = sublime.executable_path() # print('executable_path: '+ executable_path) # if sublime.platform() == 'linux': # subprocess.Popen([executable_path] + [args]) # if sublime.platform() == 'osx': # app_path = executable_path[:executable_path.rfind(".app/") + 5] # executable_path = app_path + "Contents/SharedSupport/bin/subl" # subprocess.Popen([executable_path] + args) # if sublime.platform() == "windows": # def fix_focus(): # window = sublime.active_window() # view = window.active_view() # window.run_command('focus_neighboring_group') # window.focus_view(view) # sublime.set_timeout(fix_focus, 300) ########################################################################################## #Python Util ##########################################################################################
def get_slash(): sysstr = platform.system() if(sysstr =="Windows"): slash = "\\" else: slash = "/" return slash
def get_friendly_platform_key(): friendly_platform_map = { 'darwin': 'osx', 'win32': 'windows', 'linux2': 'linux', 'linux': 'linux' } return friendly_platform_map[sys.platform] ##parse_json_from_file is from mavensmate util
def cygwin_path_handle(path): """Cygwin Path Support""" if sublime.platform() == "windows": return os.path.normcase(re.sub(cygwin_drive_regex, lambda m: "%s:/" % m.groups()[0], path)) else: return path # do nothing if it is not under windows.