Krita Scripts without Krita (Testing strategies)

Running up Krita just to test a change in your script can be a bit of a bore, … so don’t test your scripts in Krita. You can do a lot of debugging running them from the command line. The trick is to write the script so it will run properly whether it’s invoked within Krita or from the command line. You can do this with this code:

try: 
    import krita
    CONTEXT_KRITA = True
    EXTENSION = krita.Extension

except ImportError: # script being run in testing environment without Krita
    CONTEXT_KRITA = False
    EXTENSION = QWidget

You test if you can import krita. If you can, then the script is being run within Krita. Either way you set a flag CONTEXT_KRITA based on this test. You also need to set a constant EXTENSION (or DOCKER) and create your class based on this constant, rather than the base object.  For example:

class KritaScriptStarter(EXTENSION):

Rather than:

class KritaScriptStarter(krita.Extension):

That is, the superclass for your extension changes from being a Krita object (which, itself is a QWidget) to just a bare QWidget.  Then the script doesn’t have a Krita dependency.

You match this code with the following:

if  __name__ == "__main__":
    # this includes when the script is run from the command line or 
    # from the Scripter plugin.
    if CONTEXT_KRITA:
        # scripter plugin
        # give up - has the wrong context to create widgets etc. 
        # maybe in the future change this. 
        pass
    else:
        app = QApplication([])
        
        extension = KritaScriptStarter(None)
        extension.setup()
        extension.action_triggered()
        sys.exit(app.exec_())
        
elif CONTEXT_KRITA:        
    # And add the extension to Krita's list of extensions:
    app=Krita.instance()
    extension=KritaScriptStarter(parent=app) #instantiate your class
    app.addExtension(extension) 

This code checks to see what the value of __name__  is.  If __name__ == “__main__” then the script is being run from the command line (or from within krita’s scripter plugin).  If so, test for whether you’re operating in the Krita context (tested earlier when you  tried to import krita). If so, then the script is being run from within the Scripter plugin. If not, it’s being run from the command line. In that case you have to manually get your Qt application up and running (you’ll need to import QApplication earlier).

If __name__ is not “__main__” but you’re in the Krita context then you are running from within Krita, so you just set up your script as normal.

Now you can run your script equally from the command line or as a plugin from Krita.

Leave a comment