【问题标题】:Sublime Editor Plugin remember variableSublime Editor Plugin 记住变量
【发布时间】:2013-03-25 12:43:20
【问题描述】:

我正在编写一个 sublime editor 2 插件,并希望它在会话期间记住一个变量。我不希望它将变量保存为文件(它是密码),但希望能够重复运行命令,并且变量可以访问。

我希望我的插件能够像这样工作......

import commands, subprocess

class MyCommand(sublime_plugin.TextCommand):
  def run(self, edit, command = "ls"):
    try:
      thevariable
    except NameError:
      # should run the first time only
      thevariable = "A VALUE"
    else:
      # should run subsequent times
      print thevariable

【问题讨论】:

    标签: python plugins sublimetext2


    【解决方案1】:

    实现此目的的一种方法是将其设为全局变量。这将允许您从任何函数访问该变量。 Here 是一个需要考虑的堆栈问题。

    另一个选择是将它添加到类的实例中。这通常在类的__init__() 方法中完成。该方法在类对象被实例化后立即运行。有关self__init__() 的更多信息,请咨询this stack discussion。这是一个基本示例。

    class MyCommand(sublime_plugin.TextCommand):
        def __init__(self, view):
            self.view = view # EDIT
            self.thevariable = 'YOUR VALUE'
    

    这将允许您在创建类对象后访问该变量。像这样MyCommandObject.thevariable。这些类型的变量将持续到调用该方法的窗口关闭为止。

    【讨论】:

    • 我喜欢这个主意,看起来正是我想要的,但我收到了一个错误AttributeError: 'ConsoleLogCommand' object has no attribute 'view'
    猜你喜欢
    • 2021-09-10
    • 2023-03-09
    • 1970-01-01
    • 1970-01-01
    • 2016-01-16
    • 1970-01-01
    • 2020-08-26
    • 1970-01-01
    • 2017-03-02
    相关资源
    最近更新 更多