Python script fails when running from IDLE(IDE) to connect to LO Writer re error message"with Binary URP bridge disposed during call....."

Hello,

Hoping someone can help me with this problem as I spend the last two days on the internet trying to find a solution but nothing seems to work.

I have recently upgraded from LO 7.6.5.1 to LO 24.2.7.2 (x86_64) as I had this same problem before with 7.6 but I am sure I did not have the same problem with an earlier LO re 6.4.7.1 but I could be mistaken.

Basically I am trying to connect to an open LO session ie Writer for example from running a Python script in the native IDLE(IDE) but it crashes at the following line.

desktop = smgr.createInstanceWithContext( “com.sun.star.frame.Desktop”,ctx)
The error message is as below.

desktop = smgr.createInstanceWithContext( “com.sun.star.frame.Desktop”,ctx)
com.sun.star.uno.RuntimeException: Binary URP bridge disposed during call at C:/cygwin64/home/buildslave/source/libo-core/binaryurp/source/bridge.cxx:613

The strange thing is that I can run the same script from the command line and it connects to a running LO Writer session or Calc etc which was either created by the following line in the External Python script.

subprocess.Popen(‘C:\Program Files\LibreOffice\program\soffice --accept=“socket,host=localhost,port=2002;urp;” --writer’)

or by opening LO as a server from the command line with the line above minus the path.

I have tried adding to the sys paths in Python and the Path Env Var in Windows to point towards the LO program dir among others but that did not make a difference and after 2 days of internet searching for some guidance, in the end throwing my laptop against the wall didn’t do much good either!!!. :rage:

I think/guessing it may be to do with either PyUno and what is going on under the bonnet or IDLE is doggedly using the native Python.exe and not the LO Python.exe but I cannot be sure.

All the scripts /OO help etc I have seen are all mostly the same in the connection process and from what I can gather from the comments…they work, but mine just won’t.

I am using IDLE as I want to use Python’s Tkinter(which is all working fine) which in turn I will be connecting to a open LO Writer/Calc session.

What I am doing wrong??
Please can somebody kindly advise me or point me in the right direction.

My setup is as following

Windows 7 SP1
LibreOffice 24.2.7.2(x86_64)
Python (Native) 3.8.18

Sorry for the essay but I wanted to get all the info in.

Many thanks in advance. :smile:
P.R

There are compatibility reasons why LibreOffice comes with its own Python runtime C:\program files\LibreOffice\program\python.exe. Point your IDE to that Python runtime.

Hi Villeroy,

Thanks for the quick reply.

I am sorry if I sound stupid, but when you say “Point your IDE to that Python runtime”, what do you mean?

I know if I fire up LO python.exe if brings up the Python command prompt and I can run the script ok from there but that is no different to what I did above with the Windows CMD prompt.

I think I might have misunderstood what you mean but please can you explain how I would point IDLE(IDE) or my script to LO Python.exe?

Many thanks :smile:
P.R

The Python runtime compiles binary .pyc files to be executed. If your IDE produces .pyc with your installed Python runtime while LibreOffice uses another runtime, the binary files may be incompatible to each other. As far as I understand (I don’t understand much about binaries), the Python runtimes are compatible when they are compiled by the same C++ compilers with the same compilation flags.

Hi Villeroy,

Thanks for the reply.

So, based on what I think you were suggesting, I did the following.

Added to Windows Env Paths a PythonPath var pointing to the LO Python.exe.

I tried running the Native Python.exe from the Win7 command prompt which included the args to exec idle.pyw but this didnt work.

If I run the LO python.exe with the file idle.pyw which is the starting file to get (IDLE) IDE running, the LO python.exe has a problem in locating the relevant files/modules needed even though the paths are there if I check with sys.path.

If however I run the Native python.exe with exactly the same args then it fires up the (IDLE) IDE no problem.

I can, if running a script in IDLE, create a server connection with LO and open LO python.exe from that same script, then by means of using Subprocess run another script as an argument in python.exe, run a python script to make a connection to the LO server connection and do what ever but I have to keep reopening python.exe if I want to make a change etc which all seems a bit long winded.

In short I cannot connect to a running instance of LO via IDLE in one script as below which am sure I could a few years ago as the LO python cannot start the importing process of modules to start the IDLE (IDE) which the Native python does… :confused:

import sys
import socket # only needed on win32-OOo3.0.0
import uno

’ get the uno component context from the PyUNO runtime
localContext = uno.getComponentContext()

’ create the UnoUrlResolver
resolver = localContext.ServiceManager.createInstanceWithContext(
“com.sun.star.bridge.UnoUrlResolver”, localContext )

’ connect to the running office
ctx = resolver.resolve( “uno:socket,host=localhost,port=2002;urp;StarOffice.ComponentContext” )
smgr = ctx.ServiceManager

get the central desktop object ---- this is the cause of the binary URP error message above

desktop = smgr.createInstanceWithContext( “com.sun.star.frame.Desktop”,ctx)

’ access the current writer document
model = desktop.getCurrentComponent()

’ access the document’s text property
text = model.Text

'create a cursor
cursor = text.createTextCursor()

'insert the text into the document
text.insertString( cursor, “Hello World”, 0 )

If I enter all the actual script lines above one by one into the LO Python.exe having already started LO writer with a server connection then it works…just not in an actual Python script run from IDLE.

Not sure what is going on or even how to start IDLE using LO Python.exe not Native Python.exe??

Any help or advice would be most welcome.

Many thanks
P.R

I’m sorry, I have many years without Windows. I used this script for connect to LibreOffice for many years. Look if is util for you.

#!/usr/bin/env python

import uno
import socket
import subprocess
import time


class LIBO(object):
    HOST = 'localhost'
    PORT = '8100'
    ARG = f'socket,host={HOST},port={PORT};urp;StarOffice.ComponentContext'
    CMD = ['soffice',
        '-env:SingleAppInstance=false',
        '-env:UserInstallation=file:///tmp/LIBO_Process8100',
        '--headless', '--norestore', '--nologo', f'--accept={ARG}']

    def __init__(self):
        self._app = None
        self._start_office()
        if self.is_running:
            print('Conectado...')
            ctx = uno.getComponentContext()
            service = 'com.sun.star.bridge.UnoUrlResolver'
            resolver = ctx.ServiceManager.createInstanceWithContext(service, ctx)
            self._ctx = resolver.resolve(f'uno:{self.ARG}')
            self._sm = self._ctx.ServiceManager
            self._desktop = self._create_instance('com.sun.star.frame.Desktop')

    def _start_office(self):
        if self.is_running:
            return

        print('Conectando...')
        for i in range(3):
            self._app = subprocess.Popen(self.CMD,
                stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            time.sleep(5)
            if self.is_running:
                break
        return

    def _create_instance(self, name, with_context=True):
        if with_context:
            instance = self._sm.createInstanceWithContext(name, self._ctx)
        else:
            instance = self._sm.createInstance(name)
        return instance

    @property
    def is_running(self):
        try:
            s = socket.create_connection((self.HOST, self.PORT), 5.0)
            s.close()
            return True
        except ConnectionRefusedError:
            return False

    def new(self, type_doc='calc'):
        url = f'private:factory/s{type_doc}'
        doc = self._desktop.loadComponentFromURL(url, '_default', 0, ())
        return doc

    def close(self):
        if self.is_running:
            if not self._desktop is None:
                self._desktop.terminate()
            if not self._app is None:
                self._app.terminate()
        print('Desconectado...')
        return


def main():
    app = LIBO()

    doc = app.new()
    print(doc.Title)

    app.close()
    return


if __name__ == '__main__':
    main()
python libo.py
Conectando...
Conectado...
Untitled 1
Desconectado...

Best regards

Hi elmau,

No worries , thanks, and thanks for the reply.

I have tried running your above code in Python IDLE and I got a LO error message box saying the following.

**"The application cannot be started. **
The configuration file “C:\Program Files\LibreOffice\program\bootstrap.ini” is corrupt."

This is the contents of the file bootstrap.ini.

[Bootstrap]
InstallMode=
ProductKey=LibreOffice 24.2
UserInstallation=$SYSUSERCONFIG/LibreOffice/4

I don’t know what is meant by “it is corrupt” as I can open it or if what it really means is the contents are incorrect…

Any thoughts? :smile:

Hi elmau,

One of the bootstrap lines I have copied over only in part.

It should be the following.

InstallMode=<installmode>
not
InstallMode=

thanks

Hi elmau,

Just tried something else in regards to the above error message and replaced the line below…

CMD = ['soffice',
    '-env:SingleAppInstance=false',
    '-env:UserInstallation=file:///tmp/LIBO_Process8100',
    '--headless', '--norestore', '--nologo', f'--accept={ARG}']

to this

CMD = ['soffice',
    '-env:SingleAppInstance=false',
    '-env:UserInstallation=$SYSUSERCONFIG/LibreOffice/4',
    '--headless', '--norestore', '--nologo', f'--accept={ARG}']

That managed to the get LO started but in the end the same original error message I got regarding ‘Binary URP’ appeared again.

I am sure all the examples I have seen all say the same thing, that you can connect from an external source, run a Python script in that external source and connect to a running LO session ie writer etc but mine seems to fail.

Unless I am mistaken…:face_exhaling:

Any pointers please, elmau…anybody…? :smile:

Many thanks