Import scipy.stats in a macro
From Apache OpenOffice Wiki
< Python
This script was published by hanya at the OpenOffice Basic, Python, BeanShell, JavaScript.
This script imports scipy.stats to perform calculations into a Writer document.
It was getting a deadlock during the calculation of iexp in numpy.core.machar.MachAr class.
Original code
import sys
# On Linux environment, shipped Python is build with ucs2 on AOO 3.4.
# So this can not work in general. I used custom ucs4 build.
sys.path.append("/usr/lib/python2.7/dist-packages")
import threading
scipy = None
class Foo(object):
""" Scipy wrapper.
This class imports scipy module in the different thread to
avoid blocking of Python's main thread.
"""
SCIPY_IMPORTED = False
_scipy = None
_scipy_stats = None
def __init__(self):
pass
def is_imported(self):
return self.__class__.SCIPY_IMPORTED
def import_scipy(self):
""" Import scipy in another thread. """
if self.is_imported(): return True
t = threading.Thread(None, self._import_scipy)
t.start()
if t.is_alive():
t.join(5) # importing scipy needs long time
#if not self.is_imported():
# raise Exception("Failed to import scipy.")
return self.is_imported()
def _import_scipy(self):
try:
import scipy as _scipy
global scipy
scipy = _scipy
import scipy.stats as _stats
self.__class__.SCIPY_IMPORTED = True
except Exception as e:
print(e)
def scipy_stats_describe(self, a):
if self.is_imported():
return scipy.stats.describe(a)
raise Exception("Not imported.")
def run():
foo = Foo()
if foo.import_scipy():
s = foo.scipy_stats_describe((1, 2, 3, 4))
else:
s = "Failed to import"
XSCRIPTCONTEXT.getDocument().getText().setString(str(s))