3

I am writing a sublime editor 2 plugin, and would like it to remember a variable for the duration of the session. I do not want it to save the variable as a file (it is a password), but would like to be able to run a command repeatedly, and the variable to be accessible.

I want my plugin to work something like this...

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
Billy Moon
  • 57,113
  • 24
  • 136
  • 237

1 Answers1

4

One way to achieve this would be to make it a global variable. This will allow you to access that variable from any function. Here is a stack question to consider.

Another option would be to add it to the instance of the class. This is commonly done in the __init__() method of the class. This method is run as soon as the class object is instantiated. For more information on self and __init__() consult this stack discussion. Here is a basic example.

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

This will allow you to access this variable from a class object after it has been created. Something like this MyCommandObject.thevariable. These types of variables will last until the window in which the method was called from is closed.

Community
  • 1
  • 1
Alex Naspo
  • 2,052
  • 1
  • 20
  • 37
  • I like the idea, seems like exactly what I want, but I am getting an error `AttributeError: 'ConsoleLogCommand' object has no attribute 'view'` – Billy Moon Mar 25 '13 at 17:35