3

Okay so I am new with AutoKey application on my elementaryOS device and I am just playing around with some custom scripts.

What I did find strange is that there is no simple option to terminate the running script.

So, is there any nice and simple method to achieve this.

Pardon the incompetency. ._.

Adictonator
  • 141
  • 11

1 Answers1

3

Currently, there is no such method.

Autokey uses a simple mechanism to run scripts concurrently: Each script is executed inside a separate Python thread. It uses this wrapper to run scripts using the ScriptRunner class. There are some methods to kill arbitrary, running Python threads, but those methods are neither nice nor simple. You can find answers for the generic case of this question here: »Is there any way to kill a Thread in Python?«

There is one nice possibility, but it is not really simple and needs support by your scripts. You can »send« a stop signal to scripts using the global script store. The API documentation can be found here:

Suppose, this is a script you want to interrupt:

#Your script
import time
def crunch():
    time.sleep(0.01)
def processor():
    for number in range(100_000_000):
        crunch(number)
processor()

Bind a stop script like this to a hotkey:

store.set_global_value("STOP", True)

And modify your script to poll the value of the STOP variable and break if it is True:

#Your script
import time
def crunch():
    time.sleep(0.01)
def processor():
    for number in range(100_000_000):
        crunch(number)
        # Use the GLOBALS directly. If not set, use False as the default.
        if store.GLOBALS.get("STOP", False):
            # Reset the global variable, otherwise the next script will be aborted immediately.
            store.set_global_value("STOP", False)
            break
processor()

You should add such a stop check to each hot or long running code path. This won’t help if something deadlocks in your script.

luziferius
  • 66
  • 4
  • Very insightful. Thank you, sir. – Adictonator Jul 27 '18 at 21:00
  • @luziferius Why can't we use `store.get_global_value()` instead of `store.GLOBALS.get()` ? The latter only seems to work. – Cyriac Antony Sep 28 '19 at 09:19
  • Lets see the code: https://github.com/autokey/autokey/blob/86e7a85d723753143f78e0684290a362bf6789c6/lib/autokey/scripting_Store.py#L46. It returns None by default, thats why I wrote it to default to a clear False. But since None evaluates to False anyways, both ways should be fine. – luziferius Oct 01 '19 at 07:54