## Saturday, July 31, 2010

### How to start Open Office (with UNO services) from an external copy of Python

Problem Statement:

Demonstrate how to start Open Office from an external installation of Python so the pyuno library can be used to talk to the UNO interfaces in Open Office.

Target Application:

The purpose of this code snippet is to test a feature which automates Open Office from an external copy of Python (not the one shipped with Open Office).

Discussion:

There are several ways to start a process external to Python. One of the easiest is to use the  os module’s system function. This allows a command to be passed to a shell, just like it was typed at the command line. This function starts a shell and passes a string to that shell, then return execution to python once the new shell terminates.

To start Open Office so that pyuno can automate it, some command line arguments must be passed.  The following snippet illustrates how to use os.system(…) to start Open Office so pyuno can talk to it. While os.system is an easy way to start a process, it blocks execution until Open Office is closed.

import os
workingDir = 'C:\\Program Files (x86)\\OpenOffice.org 3\\program'
cmd = "\"\"" + workingDir + '\\soffice\" '+'"-accept=socket,host=localhost,port=8100;urp;StarOffice.NamingService"'
# blocking call
os.system(cmd)
# this call block execution until open office terminated
# do something after Open Office closes 

To allow a Python script to continue to execute while Open Office is running, the subprocess module offers more powerful ways to launch and control the Open Office process. The following code snippet illustrates how to start Open Office as a listener for UNO calls using subprocess.Popen(…) .

import subprocess
workingDir = 'C:\\Program Files (x86)\\OpenOffice.org 3\\program'
cmd  = workingDir + '\\soffice.exe'
opts = '"-accept=socket,host=localhost,port=8100;urp;StarOffice.NamingService"'
OOprocess = subprocess.Popen([cmd,opts])   # this call allows continued execution
# do more stuff while Open Office runs

An important difference between using subprocess.Popen(…) and os.system(…) is that subprocess.Popen(…) eliminates the need to add double quotes around path names with spaces in Windows. In fact, if you add the double quotes you will get “WindowsError: [Error 5] Access is denied” because the path and file name are not properly interpreted.

Test Environment:

• PythonXY 2.6.5.1
• Open Office 3.2.0
• Windows 7

References:

#### 1 comment:

1. Thanks for the very useful article. That was something I have been thinking of.

Could you also give some examples about how to manupilate Write and Calc documents from external Python?

Regards,

Ahmed