python 启动默认编辑器(如“webbrowser”模块)

s71maibg  于 2022-11-28  发布在  Python
关注(0)|答案(5)|浏览(145)

有没有一种简单的方法可以从Python命令行工具(比如webbrowser模块)启动系统默认编辑器?

aamkag61

aamkag611#

在Windows下,您只需“执行”文件,系统将采取默认操作:
os.system('c:/tmp/sample.txt')
对于这个例子,将生成一个默认的编辑器。在UNIX下有一个名为EDITOR的环境变量,因此您需要使用类似如下的内容:
os.system('%s %s' % (os.getenv('EDITOR'), filename))

carvr3hs

carvr3hs2#

现代Linux打开文件的方式是使用xdg-open;但是它并不能保证文本编辑器能够打开文件。如果你的程序是面向命令行的(以及你的用户),使用$EDITOR是合适的。

xriantvc

xriantvc3#

如果需要打开文件进行编辑,您可能会对this question感兴趣。

6g8kf2rb

6g8kf2rb4#

实际上,您可以使用webbrowser模块来实现这一点。到目前为止,针对此问题和相关问题给出的所有答案都是webbrowser模块在幕后所做的事情。
唯一的区别是如果他们有$EDITOR集,这是罕见的。所以也许一个更好的流程会是:

editor = os.getenv('EDITOR')
if editor:
    os.system(editor + ' ' + filename)
else:
    webbrowser.open(filename)

好的,现在我已经告诉你了,我应该让你知道,web浏览器模块确实声明它不支持这种情况。
请注意,在某些平台上,尝试使用此函数打开文件名,可能会工作并启动操作系统的相关程序。但是,它既不受支持,也不可移植。
因此,如果它不工作,不要提交错误报告。但对于大多数用途,它应该工作。

pu82cl6c

pu82cl6c5#

作为python Y-Principle generator的提交者,我需要检查生成的文件是否与原始文件一致,并希望从python调用一个支持diff-capable的编辑器。我的搜索指向了这些问题,most upvoted answer有一些评论和后续问题,我也想解决这些问题:

  • 确保使用EDITOR env变量(如果已设置)
  • 确保在MacOS上运行(在我的例子中默认为Atom)
  • 确保文本可以在临时文件中打开
  • 确保这如果一个url是打开的html文本是提取默认

在我的项目的存储库中,您可以在editory.py找到解决方案,在test_editor.py找到测试用例。

测试代码

'''
Created on 2022-11-27
@author: wf
'''
from tests.basetest import Basetest
from yprinciple.editor import Editor

class TestEditor(Basetest):
    """
    test opening an editor
    """
    
    def test_Editor(self):
        """
        test the editor
        """
        if not self.inPublicCI():
            # open this source file
            Editor.open(__file__)
            Editor.open("https://stackoverflow.com/questions/1442841/lauch-default-editor-like-webbrowser-module")
            Editor.open_tmp_text("A sample text to be opened in a temporary file")

屏幕截图x1c 0d1x
源代码

'''
Created on 2022-11-27

@author: wf
'''
from sys import platform
import os
import tempfile
from urllib.request import urlopen
from bs4 import BeautifulSoup

class Editor:
    """
    helper class to open the system defined editor
    
    see https://stackoverflow.com/questions/1442841/lauch-default-editor-like-webbrowser-module
    """
    
    @classmethod
    def extract_text(cls,html_text:str)->str:
        """
        extract the text from the given html_text
        
        Args:
            html_text(str): the input for the html text
            
        Returns:
            str: the plain text 
        """
        soup = BeautifulSoup(html_text, features="html.parser")

        # kill all script and style elements
        for script in soup(["script", "style"]):
            script.extract()    # rip it out
        
        # get text
        text = soup.get_text()
        
        # break into lines and remove leading and trailing space on each
        lines = (line.strip() for line in text.splitlines())
        # break multi-headlines into a line each
        chunks = (phrase.strip() for line in lines for phrase in line.split("  "))
        # drop blank lines
        text = '\n'.join(chunk for chunk in chunks if chunk)
        return text

    @classmethod
    def open(cls,file_source:str,extract_text:bool=True)->str:
        """
        open an editor for the given file_source
        
        Args:
            file_source(str): the path to the file
            extract_text(bool): if True extract the text from html sources
            
        Returns:
            str: the path to the file e.g. a temporary file if the file_source points to an url
        """
        # handle urls
        # https://stackoverflow.com/a/45886824/1497139
        if file_source.startswith("http"):
            url_source = urlopen(file_source)
            #https://stackoverflow.com/a/19156107/1497139
            charset=url_source.headers.get_content_charset()
            # if charset fails here you might want to set it to utf-8 as a default!
            text = url_source.read().decode(charset)
            if extract_text:
                # https://stackoverflow.com/a/24618186/1497139
                text=cls.extract_text(text)
                
            return cls.open_tmp_text(text)
            
        editor_cmd=None
        editor_env=os.getenv('EDITOR')
        if editor_env:
            editor_cmd=editor_env
        if platform == "darwin":
            if not editor_env:
                # https://stackoverflow.com/questions/22390709/how-can-i-open-the-atom-editor-from-the-command-line-in-os-x
                editor_cmd="/usr/local/bin/atom"
        os_cmd=f"{editor_cmd} {file_source}"
        os.system(os_cmd)
        return file_source
        
    @classmethod
    def open_tmp_text(cls,text:str)->str:
        """
        open an editor for the given text in a newly created temporary file
        
        Args:
            text(str): the text to write to a temporary file and then open
        
        Returns:
            str: the path to the temp file
        """
        # see https://stackoverflow.com/a/8577226/1497139
        # https://stackoverflow.com/a/3924253/1497139
        with tempfile.NamedTemporaryFile(delete=False) as tmp:
            with open(tmp.name,"w") as tmp_file:
                tmp_file.write(text)
                tmp_file.close()
            return cls.open(tmp.name)

堆栈溢出答案已应用

相关问题