在Python中替换string并使用result打开浏览器



我正试图为程序Sublimetext2构建一个插件。

使用Python编写的插件。我完全没有Python知识,但从现有的插件和我的PHP知识来看,这里是我需要帮助的…

这是到目前为止Python文件的开始

import sublime, sublime_plugin
import webbrowser
settings = sublime.load_settings('openonserver.sublime-settings')
settings.get('file_path_prefix')
settings.get('server_url')
class OpenonServerCommand(sublime_plugin.TextCommand):
   def run(self,edit):
      file_path = self.view.file_name()

我需要做的是取settings

的值

file_path将是我运行这个文件的路径,所以我们说…

E:Serverhtdocsmytest_project_somefolder_test.php

设置

file_path_prefixE:Serverhtdocs

server_url将成为http://localhost/

我需要看看file_path_prefix是否存在于file_path中如果存在,

我需要用http://localhost/替换E:Serverhtdocs,并将所有替换为/,然后将此新路径存储在变量

所以…E:Serverhtdocsmytest_project_somefolder_test.php将变成

http://localhost/mytest_project_/some/folder_/test.php

然后我需要把这个发送给浏览器。

任何帮助都非常感谢

使用

os.system("path_to_browser url")

运行任何外部程序。我还建议大家看一下这个注释

好了,经过几个小时(我现在讨厌Python)我的解决方案(我非常不印象深刻),但它部分有效

#Context.sublime-menu
[
    { "command": "openserver", "caption": "Open on Server" }
]
#Default (Windows).sublime-keymap
[
        { "keys": ["ctrl+shift+b"], "command": "openserver" }
]
#Main.sublime-menu
[
    {
        "caption": "Tools",
        "mnemonic": "T",
        "id": "tools",
        "children":
        [
            { "command": "openserver", "caption": "Open on Server" }
        ]
    }
]
#Openserver.sublime-commands
[
    {
        "caption": "Open file on Server in Browser",
        "command": "openserver"
    }
]

#Openserver.sublime-settings
{
    "file_path_prefix": "E:/Server/htdocs",
    "url_prefix": "http://localhost"
}
主文件

#openserver.py  
import sublime, sublime_plugin
import os
import webbrowser
import re
import os2emxpath
import logging
import sys
class OpenserverCommand(sublime_plugin.TextCommand):
   def run(self,edit):
    file_path = self.view.file_name()
    settings = sublime.load_settings('Openserver.sublime-settings')
    file = os2emxpath.normpath(file_path)
    url = re.sub(settings.get('file_path_prefix'), settings.get('url_prefix'), file)
    #logging.warning(url)
    #webbrowser.open_new(url)
    if sys.platform=='win32':
        os.startfile(url)
    elif sys.platform=='darwin':
        subprocess.Popen(['open', url])
    else:
        try:
            subprocess.Popen(['xdg-open', url])
        except OSError:
            logging.warning(url)

正常但部分不正常,它会取文件名,替换设置文件中的路径和服务器URL然后用正确的URL启动浏览器

除了,在Sublimetext2中,当你在一个。py文件或任何你没有设置能够在web浏览器中打开的文件上运行这个,然后不是在web浏览器中打开文件,它会给窗口弹出要求设置一个默认程序来打开文件,非常烦人!

最新更新