Python3 Binding (Discussion)

looks like you are using a venv setup, but without native modules enabled.

Currently, openhab has a bug, which prevents using the webui config dialog for kar based Add-ons. For that reason, you need to configure the Add-on with a config file in /openhab/conf/services/pythonscripting.cfg

below, you find the default config

# Use scope and import wrapper
#
# This enables a scope module and and import wrapper.
# An scope module is an encapsulated module containing all openHAB jsr223 objects and can be imported with <code>import scope</code>
# Additionally you can run an import like <code>from org.openhab.core import OpenHAB</code>
#
#org.openhab.automation.pythonscripting:scopeEnabled = true

# Install openHAB Python helper module (requires scope module)
#
# Install openHAB Python helper module to support helper classes like rule, logger, Registry, Timer etc...
# If disabled, the openHAB python helper module can be installed manually by copying it to /conf/automation/python/lib/openhab"
#
#org.openhab.automation.pythonscripting:helperEnabled = true

# Inject scope and helper objects into rules (requires helper modules)
#
# This injects the scope and helper Registry and logger into rules.
#
# 2 => Auto injection enabled only for UI and Transformation scripts (preferred)
# 1 => Auto injection enabled for all scripts
# 0 => Disable auto injection and use 'import' statements instead
#
#org.openhab.automation.pythonscripting:injectionEnabled = 2

# Enables native modules (requires a manually configured venv)
#
# Native modules are sometimes necessary for pip modules which depends on native libraries.
#
#org.openhab.automation.pythonscripting:nativeModules = false

# Enable dependency tracking
#
# Dependency tracking allows your scripts to automatically reload when one of its dependencies is updated.
# You may want to disable dependency tracking if you plan on editing or updating a shared library, but don't want all
# your scripts to reload until you can test it.
#
#org.openhab.automation.pythonscripting:dependencyTrackingEnabled = true

# Cache compiled openHAB Python modules (.pyc files)
#
# Cache the openHAB python modules for improved startup performance.<br>
# Disable this option will result in a slower startup performance, because scripts have to be recompiled on every startup.
#
#org.openhab.automation.pythonscripting:cachingEnabled = true

# Enable jython emulation
#
# This enables Jython emulation in GraalPy. It is strongly recommended to update code to GraalPy and Python 3 as the emulation can have performance degradation.
# For tips and instructions, please refer to <a href="https://www.graalvm.org/latest/reference-manual/python/Modern-Python-on-JVM">Jython Migration Guide</a>.
#
#org.openhab.automation.pythonscripting:jythonEmulation = false

The error itself was already mentioned in the README. Additionally, I added the hint, how to configure the Add-on via a config file


If you want to avoid native modules. You can do simple get REQUEST using the HTTP action from openHAB like below

from openhab.actions import HTTP

response = HTTP.sendHttpGetRequest("https://www.openhab.org/")

print(response)

Thanks!

When do You think that it will be fixed in OpenHAB GA versions? (5.1, 5.2
)

Until then I’ll do some tests and see.

/ Valter

There is no need to wait. The Add-on itself works perfectly. Regardless of whether it is part of openHAB or comes separately via the marketplace. The only thing which does not work is the web ui config dialog for the marketplace version. But there is a workaround if you use the file based configuration.

@Nadahar is working on refactoring the way how Add-on are installed. Hopefully this fixes the web ui config dialog too. But I don’t know when we can expect results here.


Currently the venv setup is only be available in the marketplace version. The release procedure is always be the same. There is a version, merged and released with openHAB 5.0. And there is a marketplace version with newer features. In the moment, when the marketplace version is merged with openHAB 5.1, there will be a successor marketplace version again which will be merged with the openHAB 5.2.

The current marketplace version has already an open pull request which will be released as part of openHAB 5.1

My work has basically ground to a halt, partly because I haven’t found a way to solve the whole “features” mess, and partly because I have too many open PRs that aren’t getting reviewed so I’ve decided not to spend any more time on Core until that changes. There’s no point in me spending time and energy on something that will never be used. So, don’t hold your breath for a solution to this anytime soon :worried:

I think it is also not a show stopper. The official Add-on works, including the web ui config dialog. This means, if the current marketplace version is merged, the web ui config dialog works here too. And for the kar file based marketplace version exists a workaround, if you use the config file based way.

1 Like

:warning:

An important bugfix release for openhab5 is available.

If you upgrade from OpenHab 5.0.0 to 5.0.1, the old Add-on version will mess up your openHab system. It has a wrong dependency and will therefore install all core bundles from version 5.0.0 in addition to the core bundles from version 5.0.1.

This update fixes this bug.

1 Like

Will it be possible in the future to setup several VEnvs inside a rule without logging into openHAB console? How can I decide which rule is using what VEnv?

This is currently not possible. But graalpy team will release in ~2 month a major update with a huge improved venv handling. Let’s see, what this means.

I think that several VEnvs can be created like this. At the moment this needs to be done at the console.

graalpy -m venv <venv-dir>

Then we actually only need a way to activate the VEnv before the Python Rule is executed.

source <venv-dir>/bin/activate

Could something like a VEnv action in the Rule be introduced which selects the VEnv before “Execute an inline script” is executed.

I think that might be problematic, because I don’t think there’s a way to control the order in which Actions are executed. I.e., they aren’t supposed to rely on each other, but be independent, so there is no defined order. The Actions will run in serial (thus wait for each other to complete), and they will most likely be run in the same order each time, but you won’t control the order, so the “VEnv” activation might run after the Python script.

The order would depend on how the “parser” that inserts the rule in OH Core works, for a managed rule that would probably be ManagedRuleProvider. Even if you found a way to make sure it ran in a specific order for ManagedRuleProvider, it could change if another provider was used.

If the Actions were sorted by e.g Action ID before being executed, the order could easily be controlled by changing the IDs, but that would require a change in the above code in Core.

This was just a comment to the concept of using one Action to prepare for another. I have no idea if using an Action to set up a VEnv is viable.

Thanks for the information! Then maybe something like a Rule Metadata similar what we have for Item Metadata would be a better approach. If a VEnv Metadata with a certain VEnv is defined then it will activate this VEnv before the script is executed.

This could be a solution, but it is touching more the core part of openHAB.

From the pythonscripting perspective, I want to wait until the new major update of graalpy. Before I don’t want to spent more time into this topic. Otherwise we implement solutions which may be obsolete with the new way of handling venv. They announced to me that a lot of things will change in this direction.

Question about UI created Python rules:

Is there an easy way to figure out what has triggered a rule (in the code in the rule)?

Like with javascript where I can use itemNameThatTriggeredTheEvent = event.itemName;

OH version 5.0.1

Best Regards, Valter

just use

event.getItemName()

Hm, AttributeError, foreign object has no attribute ‘getItemName’

I suppose that I need to import something


Best Regards, Valter

no, the is no need to import anything.

pythonscripting is just forwarding the java api.

I just checked

print(event.getItemName())

and it works. If it does not work for you, this means it is not an “ItemEvent”

only an ItemEvent has the function getItemName

can you check the type of you event by calling

print(event.getType())

e.g. if you manually trigger the rule, you get an “ExecutionEvent” which does not have the mentioned function. The same happens for CronEvents etc.

Thanks,

I used this for ITEM-events

if (event.getType() == “ItemStateChangedEvent”):
print(event.getItemName())

Works fine :slight_smile:

I’ll try to find documentation about this.

Thanks!

1 Like

Thanks!

Hi,

I have a situation where a started timer dissapear:

It is in a UI rule:

Script code:

from threading import Timer
from openhab import Registry

#This part is ugly but works to see if the timer already exist.
try:
    dummy = timer
except NameError:
    timer = Timer(5, None)    #Dummy
    print("Create dummytimer")

CONST_DELAY = 120
    
#The function that the timer call when it has finished.
def timer_lights_off():
    print("Inside function timer_lights_off")
    if(str(Registry.getItem("FrontDoorOpenedClosed").getState()) == "CLOSED" and str(Registry.getItem("MotionHallway").getState()) == "OFF"):
        print("Send OFF")
        Registry.getItem("HallwayCeilingLight").sendCommand("OFF")
    else:
        print("Restart timer")
        timer = Timer(CONST_DELAY, timer_lights_off)    

if (str(Registry.getItem("HallwayCeilingLight").getState()) == "ON"):
    if(timer.is_alive()):  #This should never happen....
        print("If it happens anyway, tell me that")
        timer.cancel()
        timer = Timer(CONST_DELAY, timer_lights_off)
        timer.start()
    else:
        timer = Timer(CONST_DELAY, timer_lights_off)
        print("Start timer")
        timer.start()
else:
    if(timer.is_alive()):
        timer.cancel()
        print("Cancel timer")

 

It works perfect until there is a timer running AND I WORK with another script that has nothing to do with the above script and I get a syntax error in the other script when saveing it.

Log from the syntax error from the other script:

2025-09-17 11:22:42.569 [ERROR] [cripting.internal.PythonScriptEngine] - SyntaxError, invalid syntax (, line 22)

2025-09-17 11:22:42.570 [ERROR] [e.automation.internal.RuleEngineImpl] - Failed to compile rule ManageAcTempAndMode: Failed to compile action: 5(null in at line number 22 at column number 53)

At this situation the running timer in the first script disappears and the light does never turn off.

It seems that when I get the syntax error something in openhab restarts a little too much.

I can get around this by triggering the rule with cron every 5 minutes but that is not what I want.

Version 5.0.1

Best Regards, Valter