Home of site


Macroの杜(Python編)
[ Python for OpenOffice.org and LibreOffice ]

【 IDE 】

Macro格納場所

IDE環境構築(その1)

Python環境を便利にする

IDE環境構築(Eclipse利用)

上記stepにてEclipesにてPython開発環境は整う。しかし、Macroの実行はOOoの「ツール」=>「マクロの管理」=>「Python」からしか実行出来ない。
次にEclipseからOOoの各Applicationを起動させる方法を記す。


Boot環境構築

次に下記工程をAutomation化させる方法を記す。
「eclipseにてMacro記述」=>「eclipseからOOo Aplication起動」=>「Macro実行」


Automation化

eclipseからOOo Macroを正確に実行するにはPlugInの作成等の特殊工程が必要である。しかしながら、
 Step1 : Automationにて「 Python文法Check / Debug 」&「 Macroの実行 」にてMacroの概略を作成。
 Step2 : OOoからPython Macroを実行して、Debug Checkを行う。
この方法がPython Macro作成手順の1例になると思います。




Other Site







###【 Following General No.1 】###

************【 Eclipse on WindowsXP 】************


Macro格納場所

Pre-1)[General]macro格納場所

Pythonのマクロは下記Folderに格納します。 [ マイマクロ ] << WindowsXP / OpenOffice.org >> C:\Documents and Settings\user名\Application Data\OpenOffice.org\3\user\Scripts\python\ << Window10, Windows7 / LibreOffice >> C:\Users\User名\AppData\Roaming\LibreOffice\4\user\Scripts\python\ ← verion4.0系 << Ubuntu12.04LTS / LibreOffice >> /home/[ UserName ]/.config/3/user/Scripts/python/ ← 10.04LTS : /.libreoffice/3/・・・ << CentOS5.6 >> /home/[ UserName ]/.libreoffice/3/user/Scripts/ [ OpenOffice.org( LibreOffice )のマクロ ] << WindowsXP / OpenOffice.org >> C:\Program Files\OpenOffice.org 3\Basis\share\Scripts\python\pythonSamples\ << Windows7 / LibreOffice >> C:\Program Files\LibreOffice 5\share\Scripts\python << Ubuntu10.04LTS / LibreOffice >> /usr/lib/libreoffice/basis-link/share/Script/python/ << CentOS5.6 >>


IDE環境構築(その1)

IDE-Ex-1)[General]Extension(拡張機能: APSO)によるIDE環境/python script organizer for OpenOffice and LibreOffice

python script organizer for OpenOffice and LibreOffice(※)はにゃさんのPython 用の Script Providerを基に作成された拡張機能です。 インストールは 考えるエンジニア/LibreOffice CalcでPythonマクロを使う(2)
LibreOffice Calc に Python IDE の APSO を入れてみる
を参照
  ※正式名称は Alternative python script organizer for OpenOffice and LibreOffice
[参考] 過去のAPSOの情報が残ったままの場合、以下のようなメッセージが表示される時がある。 その時は、以下のファイルの内容を確認し、情報が残っていれば、ファイルを編集 or 削除(※) する。 ※ 他の拡張機能がある時は削除は慎重に!!   C:\Users\ユーザー名\AppData\Roaming\LibreOffice\4\user\uno_packages\cache\uno_packages.pmap   


Python環境を便利にする

Pip-1)[General]Pythonのライブラリーを追加できるようにする

詳細は、fixedpoint.jp/Python環境としてのLibreOfficeをより便利に使うために (2018-03-23)を参照
pip ダウンロード元
pipでlibraryを追加する際は、pip.exeがインストールされているFolder(※1)に移動してから実行した方が良さそう。  ※1 C:\Users\user名\AppData\Roaming\Python\Python38\Scripts  (杞憂かもしれません) ※2 ~\Python37\~ はPythonのversionによって違う。LO7.1.1.2 では Pytho3.8.4 ※3 PythonのVersionが変更になった時は、pipの再インストールが必要。 以下のようなエラーがえた時の参考サイトはpipインストール時のアクセス拒否の対応メモ ERROR: Could not install packages due to an EnvironmentError: [WinError 5] アクセスが拒否されました。: 'C:\\Program Files\\LibreOffice\\program\\python-core-3.5.7\\Lib\\site-packages\\PyQt5' Consider using the `--user` option or check the permissions. [パッケージ例]  OpenCV : opencv-python(参考URL OpenCVのインストール方法)


Pip-2)[General]pipのVersion Up

[手順:Windows10 64bitの場合] ①C:\Users\user名\AppData\Roaming\Python\Python38\Scripts に移動 ②Python35.dllへのpath設定:set PATH=C:\Program Files\LibreOffice\program ③インストール済みのパッケージ一覧を確認:pip list ④pipのversion Up:python -m pip install --upgrade pip --user ⑤pipのversion確認:pip --version


Pip-3)[General]ライブラリー一覧

[手順:Windows10 64bitの場合]  pipのVersion Upも参照。 ①ライブラリー一覧:pip list 参考URL : GAMMASOFT / Pythonライブラリのインストール - pipの使い方
注意:pip list --outdated は以下のエラーが発生。 ImportError: No module named 'multiprocessing.pool' multiprocessing はPythonスクリプトファイルからの起動されることを前提としており、何らかのバイナリファイルから使用されることは考慮していない 参照URL:Qiita/windows maya (GUI環境)から multiprocessing でmayapy を使用する


Pip-4)[General]ライブラリーのアップグレード

[手順:Windows10 64bitの場合]  pipのVersion Upも参照。 ①ライブラリー一覧:pip install --upgrade [package-name] 参考URL : it-swarm.dev


Pip-5)[General]留意事項

 ① bz2モジュールに依存 : matplotlib, pandas 等   以下のサイトからの抜粋「matplotlibなどのbz2モジュールに依存するライブラリは、Windows版LibreOfficeのバグによりロード(import)時にエラーになります」   fixedpoint.jp / Python環境としてのLibreOfficeをより便利に使うために (2018-03-23)
  Bug 116412 - Bundled python fails to import bz2 on Windows      確認した外部ライブラリー( LO7.0.1.2[Python3.7] )  [ロード OK] ・beautifulsoup4  ・janome  ・keyboard  ・numpy ・opencv-python  ・pdfminer.six  ・pyautogui  ・pygame  ・pyperclip  ・pywin32  ・requests  ・requests-html  ・selenium    [ロード NG]  ・matplotlib  ・pandas  ・wordcloud  ・winocr      ② tkinterモジュール  Pythonの標準モジュールであるが、LibreOfficeにラッピングされていないので利用できない模様。  


IDE環境作成(Eclipse利用)

IDE-1)[General]Window Path追加

1)Openoffice.org付属の「python.exe」と「uno.py」があるFolderを調べる。 [ 通常Installならば下記にある ] python.exe : C:\Program Files\OpenOffice.org 3\Basis\program\python-core-2.6.1\bin uno.py : C:\Program Files\OpenOffice.org 3\Basis\program 2)WindowsのPathに追加 「スタート」=>「コントロールパネル」=>「システム」=>「詳細設定」=>「環境変数」 PATH : C:\Program Files\OpenOffice.org 3\Basis\program\python-core-2.6.1\bin;C:\Program Files\OpenOffice.org 3\Basis\program 


IDE-2)[General]Eclipse DownLoad and Install

1)下記Siteより「Eclipse Classic 3.6.0」をDownload URL : http://www.eclipse.org/downloads/ file name : eclipse-SDK-3.6-win32.zip 2)Unzip


IDE-3)[General]環境変数を調べる

コマンドプロンプトにて以下のコマンドを実施 c:\python >> import os >> os.environ['URE_BOOTSTRAP'] >> os.environ['PATH'] >> os.environ['UNO_PATH'] >> <= CTL + Z + Retun(Python終了) c:\


IDE-4)[General]eclipseにpydevを追加

1)eclipse起動 workspace : C:\Documents and Settings\user名\Application Data\OpenOffice.org\3\user\Scripts\python 2)PyDev Install help => Install new Softeawe work with欄 URL : http://update-production-pydev.s3.amazonaws.com/pydev/updates/site.xml name : Pydev 「Select All」=>「Next」=>「I accept ・・・・」にCheck「Finish」=>「restart」


IDE-5)[General]Interpreter & 外部環境

Interpreter & 外部環境 設定 Window => Preferences => Pydev => Interpreter => Python Python Interpreter : C:\Documents and Settings\user名\Application Data\OpenOffice.org\3\user\Scripts\python Environment TAB PATH => C:\Program Files\OpenOffice.org 3\URE\bin;C:\Program Files\OpenOffice.org 3\Basis\program UNO_PATH => C:\Program Files\OpenOffice.org 3\Basis\program URE_BOOTSTRAP => vnd.sun.star.pathname:C:\Program Files\OpenOffice.org 3/program/fundamental.ini


IDE-6)[General]JAVA => PyDevへ切り替

右上の「JAVA」の左横にある□をClickしてPydevに切り替える。


IDE-7)[General]Pydev Project作成

1)Pydev Project作成 file => new => PyDev Project Project Name : OOoPython 2)Python Folder作成 OOoPython - src 下にpython foldef作成 3)pythonpath Folder作成 paython下にpythonpath folder作成


IDE-8)[General]ProjectのExternal Libraries設定

以下のFolderを調べておく uno.py : C:\Program Files\OpenOffice.org 3\Basis\program unohelper.py : C:\Program Files\OpenOffice.org 3\Basis\program

OOoPythonを右Click properties => PyDev-PYTHONPATH => External Libraries にuno.py onohelper.pyのPAthを追加


Projectの Properties - PyDev - PYTHONPATH の Source Folders に src 以下が含まれていることを確認


IDE-9)[General]unopy.py File作成


OOoPython - src下にunopy.py fileを作成
#
#!     # unopy.py
# -*- coding: utf_8 -*-
 
import uno
import unohelper
 
from com.sun.star.script.provider import XScriptContext
 
class ScriptContext(unohelper.Base, XScriptContext):
    def __init__(self, ctx):
        self.ctx = ctx
    
    def getComponentContext(self):
        return self.ctx
    
    def getDesktop(self):
        return self.ctx.getServiceManager().createInstanceWithContext("com.sun.star.frame.Desktop", self.ctx)
                
    def getDocument(self):
        return self.getDesktop().getCurrentComponent()
 
def connect():
    ctx = None
    try:
        localctx = uno.getComponentContext()
        resolver = localctx.getServiceManager().createInstanceWithContext(
            "com.sun.star.bridge.UnoUrlResolver", localctx)
        ctx = resolver.resolve(
            "uno:socket,host=localhost,port=2002;urp;StarOffice.ComponentContext")
        if ctx:
            return ScriptContext(ctx)
    except:
        pass
    return None

Boot環境構築

Boot-1)[General]Bat file作成

notePadにてOOoListen.batを作成 cd \ "C:\Program Files\OpenOffice.org 3\program\soffice.exe" "-accept=socket,host=localhost,port=2002;urp;StarOffice.ServiceManager"


Boot-2)[General]eclipseからCalc起動

# 下記CodeをPython以下に作成
#
#
import uno

localContext = uno.getComponentContext()
resolver = localContext.ServiceManager.createInstanceWithContext("com.sun.star.bridge.UnoUrlResolver", localContext )
ctx = resolver.resolve( "uno:socket,host=localhost,port=2002;urp;StarOffice.ComponentContext" )

smgr = ctx.ServiceManager
desktop = smgr.createInstanceWithContext( "com.sun.star.frame.Desktop",ctx)
NewDoc = desktop.loadComponentFromURL( "private:factory/scalc","_blank", 0, () )
#
#
1)OOoListen.batにてOOoをListen Modeで起動
2)test.py実行
Calcが起動すればOK

Automation化

Auto-1)[General]unopy.py変更(追加)


#!     # unopy.py
# -*- coding: utf_8 -*-
 
import uno
import unohelper
 
from com.sun.star.script.provider import XScriptContext
 
class ScriptContext(unohelper.Base, XScriptContext):
    def __init__(self, ctx):
        self.ctx = ctx
    def getComponentContext(self):
        return self.ctx
    def getDesktop(self):
        return self.ctx.getServiceManager().createInstanceWithContext(
                "com.sun.star.frame.Desktop", self.ctx)
    def getDocument(self):
        return self.getDesktop().getCurrentComponent()
 
def connect():
    ctx = None
    try:
        localctx = uno.getComponentContext()
        resolver = localctx.getServiceManager().createInstanceWithContext(
            "com.sun.star.bridge.UnoUrlResolver", localctx)
        ctx = resolver.resolve(
            "uno:socket,host=localhost,port=2002;urp;StarOffice.ComponentContext")
        if ctx:
            return ScriptContext(ctx)
    except:
        pass
    return None
    
def run_script(ctx, mod_name, func_name, location="user"):
    script_url = "vnd.sun.star.script:%s$%s?language=Python&location=%s" % (mod_name, func_name, location)
    msp = ctx.getValueByName("/singletons/com.sun.star.script.provider.theMasterScriptProviderFactory")
    sp = msp.createScriptProvider("")
    script = sp.getScript(script_url)
    return script.invoke((), (), ())
Auto-2a)[General]AutomationによるPython Macro実行(1)

以下のPython Macroの場合
#
#! # OriginalTest2.py
# -*- coding: utf_8 -*-

def hello(arg=''):
    doc = XSCRIPTCONTEXT.getDocument()
    doc.getText().setString("Hello!" if not arg else arg)

	hello("Hello! (from automation)")

をeclipseからAutomationにて実行する場合は以下の様になる。
しかも、下記CodeはOOoから実行した場合は「if __name__ == '__main__':」の結果が「false」なので、
上記Codeと同じになる。
#
#! # test2.py
# -*- coding: utf_8 -*-

def hello(arg=''):
    doc = XSCRIPTCONTEXT.getDocument()
    doc.getText().setString("Hello!" if not arg else arg)


if __name__ == '__main__':
    import uno 
    localContext = uno.getComponentContext()
    resolver = localContext.ServiceManager.createInstanceWithContext("com.sun.star.bridge.UnoUrlResolver", localContext )
    ctx = resolver.resolve( "uno:socket,host=localhost,port=2002;urp;StarOffice.ComponentContext" )
    smgr = ctx.ServiceManager
    desktop = smgr.createInstanceWithContext( "com.sun.star.frame.Desktop",ctx)
    doc = desktop.loadComponentFromURL( "private:factory/swriter","_blank", 0, () )
   
    import unopy
    XSCRIPTCONTEXT = unopy.ScriptContext(ctx)
   
    if 1: 
        hello("Hello! (from automation)")
    else:
        unopy.run_script(ctx, "test2.py", "hello", "user名")

Auto-2b)[General]AutomationによるPython Macro実行(2)


####### OOoから実行するMacro Code #########
#
#
from com.sun.star.awt import Rectangle~
 

def show_message(desktop, message):
    """shows message."""
    frame = desktop.getCurrentFrame()
    window = frame.getContainerWindow()
    toolkit = window.getToolkit()
    msgbox = toolkit.createMessageBox(
        window, Rectangle(), 'messbox', 1, '', message)
    return msgbox.execute()


def get_active_cell():
    doc = XSCRIPTCONTEXT.getDocument()
    selected = doc.getCurrentSelection()
    try:
        if selected.supportsService('com.sun.star.sheet.SheetCellRange'):
            addr = selected.getRangeAddress()
            
            txt = 'Column: %s\nRow: %s' % (addr.EndColumn, addr.EndRow)
            show_message(XSCRIPTCONTEXT.getDesktop(), txt)
    except:
        pass
#
#
####### ecipseからAutomationにて実行するCode #######
#
#
import uno
from com.sun.star.awt import Rectangle

def show_message(desktop, message):
   """shows message."""
   frame = desktop.getCurrentFrame()
   window = frame.getContainerWindow()
   toolkit = window.getToolkit()
   msgbox = toolkit.createMessageBox(
       window, Rectangle(), 'messbox', 1, '', message)
   return msgbox.execute()


def get_active_cell():
   doc = XSCRIPTCONTEXT.getDocument()
   selected = doc.getCurrentSelection()
   try:
       if selected.supportsService('com.sun.star.sheet.SheetCellRange'):
           addr = selected.getRangeAddress()
           
           txt = 'Column: %s\nRow: %s' % (addr.EndColumn, addr.EndRow)
           show_message(XSCRIPTCONTEXT.getDesktop(), txt)
   except:
       pass
   
if __name__ == '__main__':
#    import uno 
   localContext = uno.getComponentContext()
   resolver = localContext.ServiceManager.createInstanceWithContext("com.sun.star.bridge.UnoUrlResolver", localContext )
   ctx = resolver.resolve( "uno:socket,host=localhost,port=2002;urp;StarOffice.ComponentContext" )
   smgr = ctx.ServiceManager
   desktop = smgr.createInstanceWithContext( "com.sun.star.frame.Desktop",ctx)
   doc = desktop.loadComponentFromURL( "private:factory/scalc","_blank", 0, () )
  
   import unopy
   XSCRIPTCONTEXT = unopy.ScriptContext(ctx)
  
   if 1: 
       get_active_cell()
   else:
       unopy.run_script(ctx, "test3.py","" , "user名")


Top of Page

inserted by FC2 system