我正在尝试编写一个由TextCommand
和on_modified
EventListener
组成的Sublime插件。运行该命令时,它需要创建一个对象的新实例,该对象与运行view
的{{1}}相关联。每当TextCommand
在{{{}}中调用时1}},它需要使用在视图上次运行命令时生成的该类的实例。
这是我试过的:
on_modifed
我第一次运行命令时收到此消息:
EventListener
如果我修改缓冲区,它会告诉我:
from code import InteractiveConsole
class LivePythonCommand(sublime_plugin.TextCommand):
def run(self, edit):
if hasattr(self.view, 'livePythonInterpreter'):
print('Already had an interpreter, but replacing it.')
else:
print("Didn't have an interpreter, making one now.")
self.view.livePythonInterpreter = InteractiveConsole()
class LivePythonListener(sublime_plugin.EventListener):
def on_modified(self, view):
if hasattr(self.view, 'livePythonInterpreter'):
print('Modified and interpreting.')
else:
print('Modified but not interpreting.')
我再次运行命令并说:
Didn't have an interpreter, making one now.
我再次修改缓冲区,它告诉我:
Modified but not interpreting.
因此Already had an interpreter, but replacing it.
能够看到它从Modified but not interpreting.
到LivePythonCommand
分配给视图的解释器。 run
正在倾听,但它永远不会看到run
中分配给LivePythonListener
的{{1}}。我做错了什么?
答案 0 :(得分:1)
我找到了一个解决方法......我不确定我是否喜欢这个解决方案,但这里是:
from code import InteractiveConsole
livePythonInterpreters= {}
class LivePythonCommand(sublime_plugin.TextCommand):
def run(self, edit):
ic = InteractiveConsole()
global livePythonInterpreters
livePythonInterpreters[self.view.buffer_id()] = ic
class LivePythonListener(sublime_plugin.EventListener):
def on_modified(self, view):
ic = livePythonInterpreters[view.buffer_id()]
我认为很明显这是如何运作的...我只是因为需要一个全局变量而不喜欢它。如果其他人有一个没有全局变量的解决方案,我会喜欢它。