如何在Sublime Text 3 Python API中获取文件内容

时间:2016-07-26 05:57:35

标签: python sublimetext3 sublimetext sublime-text-plugin

我是Python和Sublime Text API dev的新手......所以这可能很容易?

我想将文件的内容(位于当前打开的文件旁边)显示到新的面板窗口。

我可以创建一个没有问题的新面板,并让它使用

显示一个字符串
def newLogWindow(self, output):
    window = self.view.window()

    new_view = window.create_output_panel("log")
    new_view.run_command('erase_view')
    new_view.run_command('append', {'characters': output})
    window.run_command("show_panel", {"panel": "output.log"})

    sublime.status_message('Metalang')

pass

但我需要的是一个函数来获取文件的内容以传递给该函数。

content = xxxx.open_file("filename.txt")
// somehow get contents of this file?
// pass it to log window
self.newLogWindow(content);

感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

在Sublime Text中,用于打开文件的内置API与Window绑定,并将返回与标签对应的View。在您的情况下,您希望更新一个面板(与选项卡无关的现有View)和文件内容,因此Sublime Text API不能用于此。

相反,你可以使用open method

直接在Python中完成
with open('filename.txt', 'r') as myfile:
    content = myfile.read()
    self.newLogWindow(content)