Home of site


Macroの杜( Python編 )
[ Python for LibreOffice( Apache OpenOffice ) ]

【 General No.5 】

###【 Continued from Python / General No.4 】###


**********************【 Index 】**********************

Data構造の直列化(serialize)したり非直列化(de-serialize)

[ Pickle ]

Module

Python

System[ Platform ]

[ Command ]

Windows API

Network

[ Google ]
  注意 : Google API利用にはGoogleの使用制限を順守する必要があります。
     ( Google Map上の結果表示と組み合わせる場合にのみ使用可能 等 )

[ Other ]

Regular Expression( 正規表現 )

Audio

[ Sound ]

[ Audio File ]

Japanese Coding

Internationalization / Localization

 国際化 / l18N ( I-nternationalizatio-N ) : Programを複数の言語に対応させる操作
 地域化 / l10n ( L-calizatio-N ) : 既に国際化されているProgramを特定の地域の言語や文化的な事情に対応させること



認証( authentication )

Exception( 殆どの例外は'Error'で終わる名前で定義されています。)

Other




###【 Following Python / General No.6 】###











******************************[ Macro Code ]******************************


Data構造の直列化(serialize)したり非直列化(de-serialize)

[ Pickle ]

GSzPk-)[General]文字列をSizialize化


#!
#coding: UTF-8
# python Marco
import pickle
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title',oMsgType='messbox'):
	"""shows message."""
	desktop = XSCRIPTCONTEXT.getDesktop()
	frame = desktop.getCurrentFrame()
	window = frame.getContainerWindow()
	toolkit = window.getToolkit()
	msgbox = toolkit.createMessageBox(window, MESSAGEBOX, 1, 'Title', oMessage)
	return msgbox.execute()
def oTest():
	try:
		oList = [1,2,'three','four',u'五']
		oPkDmp = pickle.dumps(oList)
		oDisp= unicode(oPkDmp,'utf-8')
	except:
		oDisp = traceback.format_exc(sys.exc_info()[2])
	finally:
		omsgbox(oDisp,1)

GSzPk-)[General]Sizialize化された文字列の復元


#!
#coding: UTF-8
# python Marco
import pickle
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title',oMsgType='messbox'):
	"""shows message."""
	desktop = XSCRIPTCONTEXT.getDesktop()
	frame = desktop.getCurrentFrame()
	window = frame.getContainerWindow()
	toolkit = window.getToolkit()
	msgbox = toolkit.createMessageBox(window, MESSAGEBOX, 1, 'Title', oMessage)
	return msgbox.execute()
def oTest():
	try:
		oList = [1,2,'three','four',u'五']
		oPkDmp = pickle.dumps(oList)
		# de-sirializze
		oPkLoad = pickle.loads(oPkDmp)
		oDisp= str(oPkLoad)
	except:
		oDisp = traceback.format_exc(sys.exc_info()[2])
	finally:
		omsgbox(oDisp,1)

GSzPk-)[General]Pickle化されたData ObjectをFileに保存


#!
#coding: UTF-8
# python Marco
import pickle
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title',oMsgType='messbox'):
	"""shows message."""
	desktop = XSCRIPTCONTEXT.getDesktop()
	frame = desktop.getCurrentFrame()
	window = frame.getContainerWindow()
	toolkit = window.getToolkit()
	msgbox = toolkit.createMessageBox(window, MESSAGEBOX, 1, 'Title', oMessage)
	return msgbox.execute()
def oTest():
	try:
		oFile = 'c:/temp/oTextPython.pickle'
		oDictionary = {'Japan':u'日本','America':u'米国','France':u'仏国'}
		#
		with open(oFile, 'wb') as f:
			pickle.dump(oDictionary, f)
		oDisp= 'Success'
	except:
		oDisp = traceback.format_exc(sys.exc_info()[2])
	finally:
		omsgbox(oDisp,1)

GSzPk-)[General]Pickle Fileの読込み


#!
#coding: UTF-8
# python Marco
import pickle
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title',oMsgType='messbox'):
	"""shows message."""
	desktop = XSCRIPTCONTEXT.getDesktop()
	frame = desktop.getCurrentFrame()
	window = frame.getContainerWindow()
	toolkit = window.getToolkit()
	msgbox = toolkit.createMessageBox(window, MESSAGEBOX, 1, 'Title', oMessage)
	return msgbox.execute()
def oTest():
	try:
		oFile = 'c:/temp/oTextPython.pickle'
		oDictionary = {'Japan':u'日本','America':u'米国','France':u'仏国'}
		# create pickle file
		with open(oFile, 'wb') as f:
			pickle.dump(oDictionary, f)
		# load pickle file
		with open(oFile, 'rb') as f2:
			oPkFile = pickle.load(f2)
		oDisp= str(oPkFile)
	except:
		oDisp = traceback.format_exc(sys.exc_info()[2])
	finally:
		omsgbox(oDisp,1)

GSzPk-)[General]











Module

GMdle-)[General]コマンドラインでのmain moduleの安全なimport

「if __name__=='__main__':」はGlobal変数の「__name__」が「__main__」と認識されると
コマンドラインを解釈するコードが実行されるので、GUI上では使用不可です。

OpenOffice.org / LibreOffice上で実行した場合
__name__=='ooo_script_framework'です。

[ 参考 ]
コマンドラインで実行する場合は以下の様にするProgramのEntry Pointが保護され、
moduleを安全にimport出来ます。

[ Good Example ]
from multiprocessing import Process, freeze_support
def foo():
	print ' Hello'
if __name__=='__main__':
	freeze_support()		# <= 通常は省略
	p = Process(target=foo)
	p.start()


[ Bad Example ]
from multiprocessing import Process
def foo():
	print ' Hello'
p = Process(target=foo)
p.start()


GMdle-)[General]Moduleのimpotと関数のimport

#
#「python_module.py」file中に関数py_funcを定義した場合
# Moduleをimportする場合
import python_module
a = python_module.py_func()
#
# 関数だけをimportする場合
from python_module import py_func()
a = py_func()
#

GMdle-)[General]組込みModule名一覧

#!
#coding: utf-8
# python Marco
import sys
import uno
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
from com.sun.star.beans import PropertyValue
import platform
def omsgbox(oMessage='',oBtnType=1,oTitle='Title'):
	"""shows message."""
	desktop = XSCRIPTCONTEXT.getDesktop()
	frame = desktop.getCurrentFrame()
	window = frame.getContainerWindow()
	toolkit = window.getToolkit()
	msgbox = toolkit.createMessageBox(window, MESSAGEBOX, oBtnType, oTitle, oMessage)
	return msgbox.execute()
def otest():
	try:
		oBltMdle = sys.builtin_module_names
		oDisp = u'[ 組込みModeule名 一覧 ]\n\n' + str(oBltMdle)
	except Exception as er:
		oDisp = ''
		oDisp = str(traceback.format_exc()) + '\n' + str(er)
	finally:
		omsgbox(oDisp,1,'LO6.4.3.2(x64)')
#
# 以下のようにLOのVersionによって組込みModuleが違うことが分かる。
#
# Python3.7.7 on LO6.4.3


# # (参考)Python2.7 on LO 3.6

GMdle-)[General]Loadされているmodule一覧


#!
#coding: utf-8
# python Marco
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title',oMsgType='messbox'):
	"""shows message."""
	desktop = XSCRIPTCONTEXT.getDesktop()
	frame = desktop.getCurrentFrame()
	window = frame.getContainerWindow()
	toolkit = window.getToolkit()
	msgbox = toolkit.createMessageBox(window, MESSAGEBOX, 1, 'Title', oMessage)
	return msgbox.execute()
def otest():
	try:
		oSys = sys.modules
		oDisp = u'[ Loadされているmodule一覧 ]\n'
		for oMdle in oSys:
			oDisp = oDisp + str(oMdle) + '\n'
	except:
		oDisp = traceback.format_exc(sys.exc_info()[2])
	finally:
		omsgbox(oDisp,1)

GMdle-)[General]Global変数一覧の取得


#!
#coding: utf-8
# python Marco
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title',oMsgType='messbox'):
	"""shows message."""
	desktop = XSCRIPTCONTEXT.getDesktop()
	frame = desktop.getCurrentFrame()
	window = frame.getContainerWindow()
	toolkit = window.getToolkit()
	msgbox = toolkit.createMessageBox(window, MESSAGEBOX, 1, 'Title', oMessage)
	return msgbox.execute()
def otest():
	try:
		oGbl = globals()
		oDisp = ''
		for k in oGbl:
			oDisp = oDisp + str(k) + '\n'
	except:
		oDisp = traceback.format_exc(sys.exc_info()[2])
	finally:
		omsgbox(oDisp)

GMdle-)[General]Local変数一覧の取得1


#!
#coding: utf-8
# python Marco
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title',oMsgType='messbox'):
	"""shows message."""
	desktop = XSCRIPTCONTEXT.getDesktop()
	frame = desktop.getCurrentFrame()
	window = frame.getContainerWindow()
	toolkit = window.getToolkit()
	msgbox = toolkit.createMessageBox(window, MESSAGEBOX, 1, 'Title', oMessage)
	return msgbox.execute()
def otest():
	try:
		oLocal_1 = 'PythonMacro'
		oLocal_2 = 100
		oLocal_3 = [1,2,3,4]
		oLocal_4 = {1:'a',2:'b'}
		oLcls = locals()
		oDisp = u'[ Local変数と値をDictionary型で取得 ]\n' + str(oLcls) + '\n'
		for k in oLcls:
			oDisp = oDisp + str(k) + '\n'
	except:
		oDisp = traceback.format_exc(sys.exc_info()[2])
	finally:
		omsgbox(oDisp)
#
# 関数内で変数に代入するとその変数は、その関数内でのみ有効なローカル変数になります。
# また、関数の仮引数もローカル変数です。

GMdle-)[General]Local変数一覧の取得2


#!
#coding: utf-8
# python Marco
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title',oMsgType='messbox'):
	"""shows message."""
	desktop = XSCRIPTCONTEXT.getDesktop()
	frame = desktop.getCurrentFrame()
	window = frame.getContainerWindow()
	toolkit = window.getToolkit()
	msgbox = toolkit.createMessageBox(window, MESSAGEBOX, 1, 'Title', oMessage)
	return msgbox.execute()
def otest():
	try:
		oLocal_1 = 'PythonMacro'
		oLocal_2 = 100
		oLocal_3 = [1,2,3,4]
		oLocal_4 = {1:'a',2:'b'}
		oV = vars()
		oDisp = u'[ Local変数と値をDictionary型で取得 ]\n' + str(oV) + '\n'
		for k in oV:
			oDisp = oDisp + str(k) + '\n'
	except:
		oDisp = traceback.format_exc(sys.exc_info()[2])
	finally:
		omsgbox(oDisp)

GMdle-)[General]Module情報取得


#!
#coding: utf-8
# python Marco
import inspect
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title',oMsgType='messbox'):
	"""shows message."""
	desktop = XSCRIPTCONTEXT.getDesktop()
	frame = desktop.getCurrentFrame()
	window = frame.getContainerWindow()
	toolkit = window.getToolkit()
	msgbox = toolkit.createMessageBox(window, MESSAGEBOX, 1, 'Title', oMessage)
	return msgbox.execute()
def oTest():
	try:
		oPath = 'C:\Program Files\LibreOffice 3\Basis\program\python-core-2.6.1\lib\os.py'
		oMdleInfo = inspect.getmoduleinfo(oPath)
		oDisp = '[ Module Information ]\n' + str(oMdleInfo)
	except:
		oDisp = traceback.format_exc(sys.exc_info()[2])
	finally:
		omsgbox(oDisp,1)
#
# Return値 : (name, suffix, mode, module_type) のTuple
# name  : Package Nameを含まないModule Name
# suffix  : File NameからModule Nameを除いた残りの部分 
# mode  : open() で指定されるFile Mode('r' または 'rb')
# module_type : Module Typeを示す整数で、 imp で定義している定数のいずれか

GMdle-)[General]


#!
#coding: utf-8
# python Marco
import inspect
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title',oMsgType='messbox'):
	"""shows message."""
	desktop = XSCRIPTCONTEXT.getDesktop()
	frame = desktop.getCurrentFrame()
	window = frame.getContainerWindow()
	toolkit = window.getToolkit()
	msgbox = toolkit.createMessageBox(window, MESSAGEBOX, 1, 'Title', oMessage)
	return msgbox.execute()
def oTest():
	try:
		oPath = 'C:\Program Files\LibreOffice 3\Basis\program\python-core-2.6.1\lib\os.py'
		oMdleName = inspect.getmodulename(oPath)
		oDisp = '[ Module Name ]\n' + str(oMdleName)
	except:
		oDisp = traceback.format_exc(sys.exc_info()[2])
	finally:
		omsgbox(oDisp,1)

GMdle-)[General]Module内のclassを取得


#!
#coding: utf-8
# python Marco
import inspect
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title',oMsgType='messbox'):
	"""shows message."""
	desktop = XSCRIPTCONTEXT.getDesktop()
	frame = desktop.getCurrentFrame()
	window = frame.getContainerWindow()
	toolkit = window.getToolkit()
	msgbox = toolkit.createMessageBox(window, MESSAGEBOX, 1, 'Title', oMessage)
	return msgbox.execute()
def oTest():
	try:
		oDisp = u'[ Module内のclass取得 ]\n'
		for name,member in inspect.getmembers(uno):
			if inspect.isclass(member):
				oDisp = oDisp + "%s is class." % name + '\n'
	except:
		oDisp = traceback.format_exc(sys.exc_info()[2])
	finally:
		omsgbox(oDisp,1)

GMdle-)[General]ModuleかどうかCheck


#!
#coding: utf-8
# python Marco
import inspect
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title',oMsgType='messbox'):
	"""shows message."""
	desktop = XSCRIPTCONTEXT.getDesktop()
	frame = desktop.getCurrentFrame()
	window = frame.getContainerWindow()
	toolkit = window.getToolkit()
	msgbox = toolkit.createMessageBox(window, MESSAGEBOX, 1, 'Title', oMessage)
	return msgbox.execute()
def oTest():
	try:
		oDisp = u'[ uno Module内のModule取得 ]\n'
		for oName,oMember in inspect.getmembers(uno):
			if inspect.ismodule(oMember):
				oDisp = oDisp + "%s is module." % oName + '\n'
	except:
		oDisp = traceback.format_exc(sys.exc_info()[2])
	finally:
		omsgbox(oDisp,1)

GMdle-)[General]Module内のfunctionを取得


#!
#coding: utf-8
# python Marco
import inspect
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title',oMsgType='messbox'):
	"""shows message."""
	desktop = XSCRIPTCONTEXT.getDesktop()
	frame = desktop.getCurrentFrame()
	window = frame.getContainerWindow()
	toolkit = window.getToolkit()
	msgbox = toolkit.createMessageBox(window, MESSAGEBOX, 1, 'Title', oMessage)
	return msgbox.execute()
def oTest():
	try:
		oDisp = u'[ uno Module内のfunction取得 ]\n'
		for oName,oMember in inspect.getmembers(uno):
			if inspect.isfunction(oMember):
				oDisp = oDisp + "%s is function." % oName + '\n'
	except:
		oDisp = traceback.format_exc(sys.exc_info()[2])
	finally:
		omsgbox(oDisp,1)

GMdle-)[General]Module内のbuiltin関数を取得


#!
#coding: utf-8
# python Marco
import inspect
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title',oMsgType='messbox'):
	"""shows message."""
	desktop = XSCRIPTCONTEXT.getDesktop()
	frame = desktop.getCurrentFrame()
	window = frame.getContainerWindow()
	toolkit = window.getToolkit()
	msgbox = toolkit.createMessageBox(window, MESSAGEBOX, 1, 'Title', oMessage)
	return msgbox.execute()
def oTest():
	try:
		oDisp = u'[ uno Module内のbuiltin関数取得 ]\n'
		for oName,oMember in inspect.getmembers(uno):
			if inspect.isbuiltin(oMember):
				oDisp = oDisp + "%s is builtin." % oName + '\n'
	except:
		oDisp = traceback.format_exc(sys.exc_info()[2])
	finally:
		omsgbox(oDisp,1)

GMdle-)[General]指定したObjectが含まれているModuleを取得


#!
#coding: utf-8
# python Marco
import inspect
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title',oMsgType='messbox'):
	"""shows message."""
	desktop = XSCRIPTCONTEXT.getDesktop()
	frame = desktop.getCurrentFrame()
	window = frame.getContainerWindow()
	toolkit = window.getToolkit()
	msgbox = toolkit.createMessageBox(window, MESSAGEBOX, 1, 'Title', oMessage)
	return msgbox.execute()
def oTest():
	try:
		oModule = inspect.getmodule(uno)
		oDisp = u'[ 指定したObject( uno )が含まれているModule取得 ]\n'\
		+ 'inspect.getmodule(uno)\n =\n' + str(oModule)
	except:
		oDisp = traceback.format_exc(sys.exc_info()[2])
	finally:
		omsgbox(oDisp,1)

GMdle-)[General]importするmoduleの型取得


#!
#coding: utf-8
# python Marco
import imp
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title',oMsgType='messbox'):
	"""shows message."""
	desktop = XSCRIPTCONTEXT.getDesktop()
	frame = desktop.getCurrentFrame()
	window = frame.getContainerWindow()
	toolkit = window.getToolkit()
	msgbox = toolkit.createMessageBox(window, MESSAGEBOX, 1, 'Title', oMessage)
	return msgbox.execute()
#
def oTest():
	try:
		oSuffix = imp.get_suffixes()
		oDisp = u'[ importする時の型]\n [suffix, mode, type]\n'\
		+ str(oSuffix)
	except:
		oDisp = traceback.format_exc(sys.exc_info()[2])
	finally:
		omsgbox(oDisp)
#
# suffix : module fileの拡張子
# mode : 読込む時のmode。Text Fileに対しては'r',Binary Fileに対しては'rb'
# type : 1 = PY_SOURCE / 2 = PY_COMPILED / 3 = C_EXTENSION

GMdle-)[General]





Python

GPy-)[General]Pythonの各種情報取得


# 最新版のLOはSubversionを利用していないので、本Codeは動作しません。
#!
#coding: utf-8
# python Marco
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title',oMsgType='messbox'):
	"""shows message."""
	desktop = XSCRIPTCONTEXT.getDesktop()
	frame = desktop.getCurrentFrame()
	window = frame.getContainerWindow()
	toolkit = window.getToolkit()
	msgbox = toolkit.createMessageBox(window, MESSAGEBOX, 1, 'Title', oMessage)
	return msgbox.execute()
def oTest():
	try:
		oVer = sys.version
		oVer_Info = sys.version_info
		oSubVer = sys.subversion
		oDisp = u'[ PythonのVersion ( sys modeule ) ]' + '\n\
		 Version => ' + str(oVer) + '\n\
		 Version Info => ' + str(oVer_Info) + '\n\
		 Subversion => ' + str(oSubVer)
	except:
		oDisp = traceback.format_exc(sys.exc_info()[2])
	finally:
		omsgbox(oDisp) 
#
# [ .subversionのReturn ]
# (repo, branch, version)のTuple。
# repo		: リポジトリの名前
# branch	:  'trunk', 'branches/name' または 'tags/name' のいずれかの形式の文字列
# version
# => Python インタプリタが Subversion のチェックアウトから ビルドされたものならば svbversion の出力であり、
# リビジョン番号 (範囲) とローカルでの変更がある場合には最後に ‘M’ が付きます。
#  ツリーがエクスポートされたもの (または svnversion が取得できない) で、
#  branch がタグならば Include/patchlevel.h のリビジョンになります。
#  それ以外の場合には None です。

GPy-)[General]PythonのVersion確認


#!
#coding: utf-8
# python Marco
import uno
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
from com.sun.star.beans import PropertyValue
import platform
def omsgbox(oMessage='',oBtnType=1,oTitle='Title'):
	"""shows message."""
	desktop = XSCRIPTCONTEXT.getDesktop()
	frame = desktop.getCurrentFrame()
	window = frame.getContainerWindow()
	toolkit = window.getToolkit()
	msgbox = toolkit.createMessageBox(window, MESSAGEBOX, oBtnType, oTitle, oMessage)
	return msgbox.execute()
def createUnoService(service_name):
	"""Create a UNO Service By this name"""
	ctx = XSCRIPTCONTEXT.getComponentContext()
	try:
		service = ctx.ServiceManager.createInstanceWithContext(service_name, ctx)
	except:
		service = NONE
	return service
def PyGetSolar():
	try:
		oProvider = 'com.sun.star.configuration.ConfigurationProvider'
		oAccess   = 'com.sun.star.configuration.ConfigurationAccess'
		oConfigProvider = createUnoService(oProvider)
		oProp = PropertyValue()
		oProp.Name = 'nodepath'
		oProp.Value = '/org.openoffice.Setup/Product'
		properties = (oProp,)
		oSet = oConfigProvider.createInstanceWithArguments(oAccess, properties)
		OOoVer = oSet.getByName('ooSetupVersion')
	except:
		OOoVer = NONE
	return OOoVer
def otest():
	try:
		oLoVer = PyGetSolar()
		oPyVer = platform.python_version()
		oPyVerTuple = platform.python_version_tuple()
		oDisp = u'[ PythonのVersion( platform module ) ]\n LibreOffice version ⇒ ' + str(oLoVer) + u'\n\n Python version ⇒ ' + str(oPyVer)\
		+ u'\n Python version tuple ⇒ ' + str(oPyVerTuple)
	except Exception as er:
		oDisp = ''
		oDisp = str(traceback.format_exc()) + '\n' + str(er)
	finally:
		omsgbox(oDisp)

GPy-)[General]整数化したPythonのVersion


#!
#coding: utf-8
# python Marco
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title'):
	"""shows message."""
	desktop = XSCRIPTCONTEXT.getDesktop()
	frame = desktop.getCurrentFrame()
	window = frame.getContainerWindow()
	toolkit = window.getToolkit()
	msgbox = toolkit.createMessageBox(window, MESSAGEBOX, oBtnType, oTitle, oMessage)
	return msgbox.execute()
def otest():
	try:
		oSystmp = sys.hexversion
		oSys = hex(oSystmp)
		oDisp = u'[ 整数化されたPython Version ]\n => ' + str(oSys)
	except Exception as er:
		oDisp = ''
		oDisp = str(traceback.format_exc()) + '\n' + str(er)
	finally:
		omsgbox(oDisp,1,'LO6.2.4.2(x64)')
#
# 0x30507f0 => version 3.5.7
# hexversionは16進数に変換しないと値の意味は分りません。

GPy-)[General]Python実装後の名称


#!
#coding: utf-8
# python Marco
import sys
import uno
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
from com.sun.star.beans import PropertyValue
import platform
def omsgbox(oMessage='',oBtnType=1,oTitle='Title'):
	"""shows message."""
	desktop = XSCRIPTCONTEXT.getDesktop()
	frame = desktop.getCurrentFrame()
	window = frame.getContainerWindow()
	toolkit = window.getToolkit()
	msgbox = toolkit.createMessageBox(window, MESSAGEBOX, oBtnType, oTitle, oMessage)
	return msgbox.execute()
def otest():
	try:
		oPlatform = platform.python_implementation()
		oDisp = u'[ Python実装後の名称( platform module ) ]' + '\n\
		 ' + 'python_implementation => ' + str(oPlatform)
	except Exception as er:
		oDisp = ''
		oDisp = str(traceback.format_exc()) + '\n' + str(er)
	finally:
		omsgbox(oDisp,1,'LO6.4.3.2(x64)')

GPy-)[General]Version管理(Python3.3(LO4.0.1)では取得出来ない)


#!
#coding: utf-8
# python Marco
import platform
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title',oMsgType='messbox'):
	"""shows message."""
	desktop = XSCRIPTCONTEXT.getDesktop()
	frame = desktop.getCurrentFrame()
	window = frame.getContainerWindow()
	toolkit = window.getToolkit()
	msgbox = toolkit.createMessageBox(window, MESSAGEBOX, 1, 'Title', oMessage)
	return msgbox.execute()
def otest():
	try:
		oPlatform1 = platform.python_branch()
		oPlatform2 = platform.python_revision()
		oDisp = u'[ Version管理( platform module ) ]' + '\n\
		 ' + 'python_branch => ' + str(oPlatform1) + '\n\
		 ' + 'python_revision => ' + str(oPlatform2)
	except:
		oDisp = traceback.format_exc(sys.exc_info()[2])
	finally:
		omsgbox(oDisp)

GPy-)[General]Build & Complier情報


#!
#coding: utf-8
# python Marco
import platform
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title'):
	"""shows message."""
	desktop = XSCRIPTCONTEXT.getDesktop()
	frame = desktop.getCurrentFrame()
	window = frame.getContainerWindow()
	toolkit = window.getToolkit()
	msgbox = toolkit.createMessageBox(window, MESSAGEBOX, oBtnType, oTitle, oMessage)
	return msgbox.execute()
def otest():
	try:
		oPlatform1 = platform.python_build()
		oPlatform2 = platform.python_compiler()
		oDisp = u'[ Build & Complier情報( platform module ) ]' + '\n\
		 ' + 'python_build => ' + str(oPlatform1) + '\n\
		 ' + 'python_compiler => ' + str(oPlatform2)
	except Exception as er:
		oDisp = ''
		oDisp = str(traceback.format_exc()) + '\n' + str(er)
	finally:
		omsgbox(oDisp,1,'LO6.2.4.2(x64)')

GPy-)[General]Copy Right取得


#!
#coding: utf-8
# python Marco
import sys
import uno
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
from com.sun.star.beans import PropertyValue
import platform
def omsgbox(oMessage='',oBtnType=1,oTitle='Title'):
	"""shows message."""
	desktop = XSCRIPTCONTEXT.getDesktop()
	frame = desktop.getCurrentFrame()
	window = frame.getContainerWindow()
	toolkit = window.getToolkit()
	msgbox = toolkit.createMessageBox(window, MESSAGEBOX, oBtnType, oTitle, oMessage)
	return msgbox.execute()
def otest():
	try:
		oCpRight = sys.copyright
		oDisp = u'[ Copy Right ]\n\n' + str(oCpRight)
	except Exception as er:
		oDisp = ''
		oDisp = str(traceback.format_exc()) + '\n' + str(er)
	finally:
		omsgbox(oDisp,1,'LO6.4.3.2(x64)')

GPy-)[General]DLLのベースアドレスのHandle値(整数値)


#!
#coding: utf-8
# python Marco
import sys
import uno
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
from com.sun.star.beans import PropertyValue
import platform
def omsgbox(oMessage='',oBtnType=1,oTitle='Title'):
	"""shows message."""
	desktop = XSCRIPTCONTEXT.getDesktop()
	frame = desktop.getCurrentFrame()
	window = frame.getContainerWindow()
	toolkit = window.getToolkit()
	msgbox = toolkit.createMessageBox(window, MESSAGEBOX, oBtnType, oTitle, oMessage)
	return msgbox.execute()
def otest():
	try:
		oCpRight = sys.dllhandle
		oDisp = u'[ Copy Right ]\n\n' + str(oCpRight)
	except Exception as er:
		oDisp = ''
		oDisp = str(traceback.format_exc()) + '\n' + str(er)
	finally:
		omsgbox(oDisp,1,'LO6.4.3.2(x64)')
#
# Only Windows
# DLL : Dynamic Link Library

GPy-)[General]Pythonの実行Fileの格納Directory


#!
#coding: utf-8
# python Marco
import sys
import uno
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
from com.sun.star.beans import PropertyValue
import platform
def omsgbox(oMessage='',oBtnType=1,oTitle='Title'):
	"""shows message."""
	desktop = XSCRIPTCONTEXT.getDesktop()
	frame = desktop.getCurrentFrame()
	window = frame.getContainerWindow()
	toolkit = window.getToolkit()
	msgbox = toolkit.createMessageBox(window, MESSAGEBOX, oBtnType, oTitle, oMessage)
	return msgbox.execute()
def otest():
	try:
		oCpRight = sys.exec_prefix
		oDisp = u'[ Pythonの実行File格納Directory ]\n\n' + str(oCpRight)
	except Exception as er:
		oDisp = ''
		oDisp = str(traceback.format_exc()) + '\n' + str(er)
	finally:
		omsgbox(oDisp,1,'LO6.4.3.2(x64)')

GPy-)[General]Pythonの実行Fileの格納Directory2


#!
#coding: utf-8
# python Marco
import sys
import uno
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
from com.sun.star.beans import PropertyValue
import platform
def omsgbox(oMessage='',oBtnType=1,oTitle='Title'):
	"""shows message."""
	desktop = XSCRIPTCONTEXT.getDesktop()
	frame = desktop.getCurrentFrame()
	window = frame.getContainerWindow()
	toolkit = window.getToolkit()
	msgbox = toolkit.createMessageBox(window, MESSAGEBOX, oBtnType, oTitle, oMessage)
	return msgbox.execute()
def otest():
	try:
		oSys = sys.prefix
		oDisp = u'[ path_importer_cache ]\n => ' + str(oSys)
	except Exception as er:
		oDisp = ''
		oDisp = str(traceback.format_exc()) + '\n' + str(er)
	finally:
		omsgbox(oDisp,1,'LO6.4.3.2(x64)')

GPy-)[General]PythonのSignal処理のcheck周期


#!
#coding: utf-8
# python Marco
import sys
import uno
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
from com.sun.star.beans import PropertyValue
import platform
def omsgbox(oMessage='',oBtnType=1,oTitle='Title'):
	"""shows message."""
	desktop = XSCRIPTCONTEXT.getDesktop()
	frame = desktop.getCurrentFrame()
	window = frame.getContainerWindow()
	toolkit = window.getToolkit()
	msgbox = toolkit.createMessageBox(window, MESSAGEBOX, oBtnType, oTitle, oMessage)
	return msgbox.execute()
def otest():
	try:
		oPyChk = sys.getcheckinterval()
		oDisp = u'[ PythonのSignal処理のcheck周期 ]\n\n' + str(oPyChk) + '[ bytecodes ]'
	except Exception as er:
		oDisp = ''
		oDisp = str(traceback.format_exc()) + '\n' + str(er)
	finally:
		omsgbox(oDisp,1,'LO6.4.3.2(x64)')

GPy-)[General]Pythonの再帰呼び出しの上限


#!
#coding: utf-8
# python Marco
import sys
import uno
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
from com.sun.star.beans import PropertyValue
import platform
def omsgbox(oMessage='',oBtnType=1,oTitle='Title'):
	"""shows message."""
	desktop = XSCRIPTCONTEXT.getDesktop()
	frame = desktop.getCurrentFrame()
	window = frame.getContainerWindow()
	toolkit = window.getToolkit()
	msgbox = toolkit.createMessageBox(window, MESSAGEBOX, oBtnType, oTitle, oMessage)
	return msgbox.execute()
def otest():
	try:
		oPyReLimit = sys.getrecursionlimit()
		oDisp = u'[ 再帰呼び出しの上限 ]\n => ' + str(oPyReLimit) + u' 回'
	except Exception as er:
		oDisp = ''
		oDisp = str(traceback.format_exc()) + '\n' + str(er)
	finally:
		omsgbox(oDisp,1,'LO6.4.3.2(x64)')
#
# 再帰呼び出しとは、関数内でその関数自身を実行することを言う。
# あまりにも深い再帰呼び出しによるオーバーフローを防ぐため、
# Python では、再帰呼び出しの上限を設定している。(Defaultは 1000 回)

GPy-)[General]C APIのVersion


#!
#coding: utf-8
# python Marco
import sys
import uno
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
from com.sun.star.beans import PropertyValue
import platform
def omsgbox(oMessage='',oBtnType=1,oTitle='Title'):
	"""shows message."""
	desktop = XSCRIPTCONTEXT.getDesktop()
	frame = desktop.getCurrentFrame()
	window = frame.getContainerWindow()
	toolkit = window.getToolkit()
	msgbox = toolkit.createMessageBox(window, MESSAGEBOX, oBtnType, oTitle, oMessage)
	return msgbox.execute()
def otest():
	try:
		oSys = sys.api_version
		oDisp = u'[ C APIのVersion ]\n => ' + str(oSys)
	except Exception as er:
		oDisp = ''
		oDisp = str(traceback.format_exc()) + '\n' + str(er)
	finally:
		omsgbox(oDisp,1,'LO6.4.3.2(x64)')
#
# Python と拡張モジュール間の不整合をデバッグする場合などに利用できます。

GPy-)[General]Pythonが使用するResistry Version


#!
#coding: utf-8
# python Marco
import sys
import uno
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
from com.sun.star.beans import PropertyValue
import platform
def omsgbox(oMessage='',oBtnType=1,oTitle='Title'):
	"""shows message."""
	desktop = XSCRIPTCONTEXT.getDesktop()
	frame = desktop.getCurrentFrame()
	window = frame.getContainerWindow()
	toolkit = window.getToolkit()
	msgbox = toolkit.createMessageBox(window, MESSAGEBOX, oBtnType, oTitle, oMessage)
	return msgbox.execute()
def otest():
	try:
		oSys = sys.winver
		oDisp = u'[ Pythonが使用するResistry Version ]\n => ' + str(oSys)
	except Exception as er:
		oDisp = ''
		oDisp = str(traceback.format_exc()) + '\n' + str(er)
	finally:
		omsgbox(oDisp,1,'LO6.4.3.2(x64)')
#
# Windowsプラットフォームで、レジストリのキーとなるバージョン番号。
# 通常、この値は versionの先頭三文字となります。つまり、Python version 3.7.7 ⇒ 3.7

GPy-)[General]組込関数一覧


# 下記CodeはPython2系。最新LOでは動作しません。
#!
#coding: utf-8
# python Marco
import __builtin__
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title',oMsgType='messbox'):
	"""shows message."""
	desktop = XSCRIPTCONTEXT.getDesktop()
	frame = desktop.getCurrentFrame()
	window = frame.getContainerWindow()
	toolkit = window.getToolkit()
	msgbox = toolkit.createMessageBox(window, MESSAGEBOX, 1, 'Title', oMessage)
	return msgbox.execute()
def otest():
	try:
		oBuiltin = dir(__builtin__)
		oDisp = u'[ 組込関数一覧 ]\n\n' + str(oBuiltin)
	except:
		oDisp = traceback.format_exc(sys.exc_info()[2])
	finally:
		omsgbox(oDisp,1)

GPy-)[General]Objectの識別子(id)取得


#!
#coding: utf-8
# python Marco
import sys
import uno
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
from com.sun.star.beans import PropertyValue
import platform
def omsgbox(oMessage='',oBtnType=1,oTitle='Title'):
	"""shows message."""
	desktop = XSCRIPTCONTEXT.getDesktop()
	frame = desktop.getCurrentFrame()
	window = frame.getContainerWindow()
	toolkit = window.getToolkit()
	msgbox = toolkit.createMessageBox(window, MESSAGEBOX, oBtnType, oTitle, oMessage)
	return msgbox.execute()
def otest():
	try:
		def oFunc(oVal1,oVal2):
			return oVal1 + oVal2
		class Cls():				# class名の先頭文字は大文字
			oData1 = oFunc(1,2)
			oData2 = oData1 * 3
		oChkFunc = oFunc(10,20)
		oIdF = id(oFunc)
		oIdC = id(Cls)
		oIdV = id(oChkFunc)
		oIdBlt = id(hex)
		oDisp = u'[ 識別子(id)を表す整数 ]\n User定義関数 / id(oFunc) = ' + str(oIdF) + '\n'\
		+ u'User定義Class / id(Cls) = ' + str(oIdC) + '\n'\
		+ u'変数 / id(oChkFunc) = ' + str(oIdV) + '\n'\
		+ u'組込み関数 / id(hex) = ' + str(oIdBlt)
	except Exception as er:
		oDisp = ''
		oDisp = str(traceback.format_exc()) + '\n' + str(er)
	finally:
		omsgbox(oDisp,1,'LO6.4.3.2(x64)')

GPy-)[General]呼出し可能Object Check


#!
#coding: utf-8
# python Marco
import sys
import uno
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
from com.sun.star.beans import PropertyValue
import platform
def omsgbox(oMessage='',oBtnType=1,oTitle='Title'):
	"""shows message."""
	desktop = XSCRIPTCONTEXT.getDesktop()
	frame = desktop.getCurrentFrame()
	window = frame.getContainerWindow()
	toolkit = window.getToolkit()
	msgbox = toolkit.createMessageBox(window, MESSAGEBOX, oBtnType, oTitle, oMessage)
	return msgbox.execute()
def otest():
	try:
		def oFunc(oVal1,oVal2):
			return oVal1 + oVal2
		class Cls():				# class名の先頭文字は大文字
			oData1 = oFunc(1,2)
			oData2 = oData1 * 3
		oStr = 'Hello world!!'
		oCall1 = callable(oFunc)
		oCall2 = callable(Cls)
		oCall3 = callable(oStr)
		oDisp = u'[ 呼出し可能ObjectかCheck / callable関数 ]\n\n'\
		+ 'call(oFunc) = ' + str(oCall1) + '\n'\
		+ 'call(Cls) = ' + str(oCall2) + '\n'\
		+ 'call(oStr) = ' + str(oCall3)
	except Exception as er:
		oDisp = ''
		oDisp = str(traceback.format_exc()) + '\n' + str(er)
	finally:
		omsgbox(oDisp,1,'LO6.4.3.2(x64)')

GPy-)[General]











System[ Platform ]

GSys-)[General]OS名( Platform名 )取得


#!
#coding: utf-8
# python Marco
import os
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title',oMsgType='messbox'):
	"""shows message."""
	desktop = XSCRIPTCONTEXT.getDesktop()
	frame = desktop.getCurrentFrame()
	window = frame.getContainerWindow()
	toolkit = window.getToolkit()
	msgbox = toolkit.createMessageBox(window, MESSAGEBOX, 1, 'Title', oMessage)
	return msgbox.execute()
def oTest():
	try:
		oOsTmp = os.name
		if oOsTmp == 'nt':
			oOsName = 'Windows NT系'
		elif oOsTmp == 'mac':
			oOsName = 'Mac OS'
		elif oOsTmp == 'dos':
			oOsName = 'MS-DOS'
		elif oOsTmp == 'ce':
			oOsName = 'Windows CE系'
		elif oOsTmp == 'posix':
			oOsName = 'Unix / Linux' + '\n'
			oOsName = oOsName + '(Portable Operation System Interface)'
		elif oOsTmp == 'riscos':
			oOsName = 'RISC/OS( Unix )'
		elif oOsTmp == 'java':
			oOsName = 'JavaVM'
		#
		oDisp = u'[ OS名(Platform名) ]' + '\n\
		 ' + oOsName
	except OSError:
		oDisp = 'Exception of OS Error'
	except:
		oDisp = traceback.format_exc(sys.exc_info()[2])
	finally:
		omsgbox(oDisp)

GSys-)[General]OS名( Platform名 )取得2


#!
#coding: utf-8
# python Marco
import platform
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title',oMsgType='messbox'):
	"""shows message."""
	desktop = XSCRIPTCONTEXT.getDesktop()
	frame = desktop.getCurrentFrame()
	window = frame.getContainerWindow()
	toolkit = window.getToolkit()
	msgbox = toolkit.createMessageBox(window, MESSAGEBOX, 1, 'Title', oMessage)
	return msgbox.execute()
def otest():
	try:
		oPlatform1 = platform.platform(0,0)
		oPlatform2 = platform.platform(1,0)
		oPlatform3 = platform.platform(0,1)
		oPlatform4 = platform.platform(1,1)
		oDisp = u'[ Platform( platform module ) ]' + '\n\
		 ' + '.platform(0,0) => ' + str(oPlatform1) + '\n\
		 ' + '.platform(1,0) => ' + str(oPlatform2) + '\n\
		 ' + '.platform(0,1) => ' + str(oPlatform3) + '\n\
		 ' + '.platform(1,1) => ' + str(oPlatform4)
	except:
		oDisp = traceback.format_exc(sys.exc_info()[2])
	finally:
		omsgbox(oDisp)

GSys-)[General]OS名取得3


#!
#coding: utf-8
# python Marco
import platform
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title',oMsgType='messbox'):
	"""shows message."""
	desktop = XSCRIPTCONTEXT.getDesktop()
	frame = desktop.getCurrentFrame()
	window = frame.getContainerWindow()
	toolkit = window.getToolkit()
	msgbox = toolkit.createMessageBox(window, MESSAGEBOX, 1, 'Title', oMessage)
	return msgbox.execute()
def otest():
	try:
		oPlatform1 = platform.system()
		oDisp = u'[ Platform( platform module ) ]' + '\n\
		 ' + '.system => ' + str(oPlatform1)
	except:
		oDisp = traceback.format_exc(sys.exc_info()[2])
	finally:
		omsgbox(oDisp)

GSys-)[General]OSのRelease情報取得


#!
#coding: utf-8
# python Marco
import platform
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title',oMsgType='messbox'):
	"""shows message."""
	desktop = XSCRIPTCONTEXT.getDesktop()
	frame = desktop.getCurrentFrame()
	window = frame.getContainerWindow()
	toolkit = window.getToolkit()
	msgbox = toolkit.createMessageBox(window, MESSAGEBOX, 1, 'Title', oMessage)
	return msgbox.execute()
def otest():
	try:
		oPlatform1 = platform.release()
		oDisp = u'[ Platform( platform module ) ]' + '\n\
		 ' + '.release => ' + str(oPlatform1)
	except:
		oDisp = traceback.format_exc(sys.exc_info()[2])
	finally:
		omsgbox(oDisp)

GSys-)[General]OSのVersion情報取得


#!
#coding: utf-8
# python Marco
import platform
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title',oMsgType='messbox'):
	"""shows message."""
	desktop = XSCRIPTCONTEXT.getDesktop()
	frame = desktop.getCurrentFrame()
	window = frame.getContainerWindow()
	toolkit = window.getToolkit()
	msgbox = toolkit.createMessageBox(window, MESSAGEBOX, 1, 'Title', oMessage)
	return msgbox.execute()
def otest():
	try:
		oPlatform1 = platform.version()
		oDisp = u'[ Platform( platform module ) ]' + '\n\
		 ' + '.version => ' + str(oPlatform1)
	except:
		oDisp = traceback.format_exc(sys.exc_info()[2])
	finally:
		omsgbox(oDisp)

GSys-)[General]OS名( Platform名 )取得3


#!
#coding: utf-8
# python Marco
import platform
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title',oMsgType='messbox'):
	"""shows message."""
	desktop = XSCRIPTCONTEXT.getDesktop()
	frame = desktop.getCurrentFrame()
	window = frame.getContainerWindow()
	toolkit = window.getToolkit()
	msgbox = toolkit.createMessageBox(window, MESSAGEBOX, 1, 'Title', oMessage)
	return msgbox.execute()
def otest():
	try:
		oPltfmSys = platform.system()
		oPltfmRels = platform.release()
		oPltfmVer = platform.version()
		oPlatform1 = platform.system_alias(str(oPltfmSys),str(oPltfmRels),str(oPltfmVer))
		oDisp = u'[ Platform( platform module ) ]' + '\n\
		 ' + '.system_alias => ' + str(oPlatform1)
	except:
		oDisp = traceback.format_exc(sys.exc_info()[2])
	finally:
		omsgbox(oDisp)

GSys-)[General]Architecture情報


#!
#coding: utf-8
# python Marco
import platform
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title',oMsgType='messbox'):
	"""shows message."""
	desktop = XSCRIPTCONTEXT.getDesktop()
	frame = desktop.getCurrentFrame()
	window = frame.getContainerWindow()
	toolkit = window.getToolkit()
	msgbox = toolkit.createMessageBox(window, MESSAGEBOX, 1, 'Title', oMessage)
	return msgbox.execute()
def otest():
	try:
		oPlatform1 = platform.architecture()
		oDisp = u'[ Platform( platform module ) ]' + '\n\
		 ' + '.architecture => ' + str(oPlatform1)
	except:
		oDisp = traceback.format_exc(sys.exc_info()[2])
	finally:
		omsgbox(oDisp)

GSys-)[General]各種OS情報


#!
#coding: utf-8
# python Marco
import platform
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title',oMsgType='messbox'):
	"""shows message."""
	desktop = XSCRIPTCONTEXT.getDesktop()
	frame = desktop.getCurrentFrame()
	window = frame.getContainerWindow()
	toolkit = window.getToolkit()
	msgbox = toolkit.createMessageBox(window, MESSAGEBOX, 1, 'Title', oMessage)
	return msgbox.execute()
def otest():
	try:
		oPlatform1 = platform.win32_ver()	# Window
		#oPlatform1 = platform.linux_distribution()	# Linux
		#oPlatform1 = platform.linux_dist()	# Unix
		#oPlatform1 = platform.mac_ver()	# Mac
		#oPlatform1 = platform.java_ver()	# Java
		oDisp = u'[ Platform( platform module ) ]' + '\n\
		 ' + '.win32_ver => ' + str(oPlatform1)
	except:
		oDisp = traceback.format_exc(sys.exc_info()[2])
	finally:
		omsgbox(oDisp)

GSys-)[General]OS情報 & CPU情報 & network上の認識名を取得

#!
#coding: utf-8
# python Marco
import platform
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title',oMsgType='messbox'):
	"""shows message."""
	desktop = XSCRIPTCONTEXT.getDesktop()
	frame = desktop.getCurrentFrame()
	window = frame.getContainerWindow()
	toolkit = window.getToolkit()
	msgbox = toolkit.createMessageBox(window, MESSAGEBOX, 1, 'Title', oMessage)
	return msgbox.execute()
def otest():
	try:
		oPlatform1 = platform.uname()
		oDisp = u'[ Platform( platform module ) ]' + '\n\
		 ' + '.uname => ' + str(oPlatform1)
	except:
		oDisp = traceback.format_exc(sys.exc_info()[2])
	finally:
		omsgbox(oDisp)
#
# CPUが複数あれば、複数のCPU情報が取得出来る。

GSys-)[General]Network上の認識名取得

#!
#coding: utf-8
# python Marco
import platform
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title',oMsgType='messbox'):
	"""shows message."""
	desktop = XSCRIPTCONTEXT.getDesktop()
	frame = desktop.getCurrentFrame()
	window = frame.getContainerWindow()
	toolkit = window.getToolkit()
	msgbox = toolkit.createMessageBox(window, MESSAGEBOX, 1, 'Title', oMessage)
	return msgbox.execute()
def otest():
	try:
		oPlatform1 = platform.node()
		oDisp = u'[ Platform( platform module ) ]' + '\n\
		 ' + '.node => ' + str(oPlatform1)
	except:
		oDisp = traceback.format_exc(sys.exc_info()[2])
	finally:
		omsgbox(oDisp)

GSys-)[General]CPUの簡易情報


#!
#coding: utf-8
# python Marco
import platform
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title',oMsgType='messbox'):
	"""shows message."""
	desktop = XSCRIPTCONTEXT.getDesktop()
	frame = desktop.getCurrentFrame()
	window = frame.getContainerWindow()
	toolkit = window.getToolkit()
	msgbox = toolkit.createMessageBox(window, MESSAGEBOX, 1, 'Title', oMessage)
	return msgbox.execute()
def otest():
	try:
		oPlatform1 = platform.machine()
		oDisp = u'[ Platform( platform module ) ]' + '\n\
		 ' + '.machine => ' + str(oPlatform1)
	except:
		oDisp = traceback.format_exc(sys.exc_info()[2])
	finally:
		omsgbox(oDisp)

GSys-)[General]CPUの詳細情報


#!
#coding: utf-8
# python Marco
import platform
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title',oMsgType='messbox'):
	"""shows message."""
	desktop = XSCRIPTCONTEXT.getDesktop()
	frame = desktop.getCurrentFrame()
	window = frame.getContainerWindow()
	toolkit = window.getToolkit()
	msgbox = toolkit.createMessageBox(window, MESSAGEBOX, 1, 'Title', oMessage)
	return msgbox.execute()
def otest():
	try:
		oPlatform1 = platform.processor()
		oDisp = u'[ Platform( platform module ) ]' + '\n\
		 ' + '.processor => ' + str(oPlatform1)
	except:
		oDisp = traceback.format_exc(sys.exc_info()[2])
	finally:
		omsgbox(oDisp)

GSys-)[General]CPUのエンディアン


#!
#coding: utf-8
# python Marco
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title',oMsgType='messbox'):
	"""shows message."""
	desktop = XSCRIPTCONTEXT.getDesktop()
	frame = desktop.getCurrentFrame()
	window = frame.getContainerWindow()
	toolkit = window.getToolkit()
	msgbox = toolkit.createMessageBox(window, MESSAGEBOX, 1, 'Title', oMessage)
	return msgbox.execute()
def otest():
	try:
		oByteOdr = sys.byteorder
		oDisp = u'稼働CPUのエンディアン\n => ' + str(oByteOdr)
	except SystemExit:
		oDisp = u'処理を終了します。'
	except:
		oDisp = traceback.format_exc(sys.exc_info()[2])
	finally:
		omsgbox(oDisp,1)
#
# エンディアン (endianness) とは、多バイトのデータ(即ち基本情報記憶単位を超えるデータ)をメモリ上に配置する方式の種類のこと。
# 例えば16進数で 0x1234ABCD という4バイトのデータを、
# データの上位バイトからメモリに「12 34 AB CD」と並べる方式をビッグエンディアン (big endian)、
# データの下位バイトから「CD AB 34 12」と並べる方式をリトルエンディアン (little endian) という。
# 稼動CPUを問わずJava仮想マシンについてはビッグエンディアンである。

GSys-)[General]WindowsのVersion


#!
#coding: utf-8
# python Marco
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title',oMsgType='messbox'):
	"""shows message."""
	desktop = XSCRIPTCONTEXT.getDesktop()
	frame = desktop.getCurrentFrame()
	window = frame.getContainerWindow()
	toolkit = window.getToolkit()
	msgbox = toolkit.createMessageBox(window, MESSAGEBOX, 1, 'Title', oMessage)
	return msgbox.execute()
def otest():
	try:
		oWinVer = sys.getwindowsversion()
		oDisp = u'[ WindowsのVersion ]\n => ' + str(oWinVer)
	except:
		oDisp = traceback.format_exc(sys.exc_info()[2])
	finally:
		omsgbox(oDisp,1)
#
# Tuple値 => (majar,minor,build,platform,text)
# [ platform値 ]
# 0	: Windows 3.1
# 1	: Windows 95/98/ME
# 2	: Windows NT/2000/XP/VISTA/7
# 3	: Windows CE

GSys-)[General]




GSys-)[General]











[ Command ]

GSys-)[General]Command実行


#!
#coding: utf-8
# python Marco
import os
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title',oMsgType='messbox'):
	"""shows message."""
	desktop = XSCRIPTCONTEXT.getDesktop()
	frame = desktop.getCurrentFrame()
	window = frame.getContainerWindow()
	toolkit = window.getToolkit()
	msgbox = toolkit.createMessageBox(window, MESSAGEBOX, 1, 'Title', oMessage)
	return msgbox.execute()
def oTest():
	try:
		os.system('notepad.exe c:\\temp\\Dummy.txt')
		# os.system('dir')	# Windows
		# os.system('ls')	# Unix, Linux
		#
		oDisp = 'Success'
	except:
		oDisp = traceback.format_exc(sys.exc_info()[2])
	finally:
		omsgbox(oDisp,1)

GSys-)[General]Subprocess実行(完了を待たない)

#!
#coding: utf-8
# python Marco
import subprocess
import uno
import sys, traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title'):
	"""shows message."""
	desktop = XSCRIPTCONTEXT.getDesktop()
	frame = desktop.getCurrentFrame()
	window = frame.getContainerWindow()
	toolkit = window.getToolkit()
	msgbox = toolkit.createMessageBox(window, MESSAGEBOX, oBtnType, oTitle, oMessage)
	return msgbox.execute()
def oTest():
	try:
		cmd='mspaint.exe'
		subprocess.Popen(cmd, shell=True)
		oDisp = str('Success')
	except Exception as er:
		oDisp = ''
		oDisp = str(traceback.format_exc()) + '\n' + str(er)
	finally:
		omsgbox(oDisp,1,'LO7.0.1.2')
#
# Subprocess : https://docs.python.org/ja/3/library/subprocess.html

GSys-)[General]Subprocess実行(完了を待つ)

#!
#coding: utf-8
# python Marco
import subprocess
import uno
import sys, traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title'):
	"""shows message."""
	desktop = XSCRIPTCONTEXT.getDesktop()
	frame = desktop.getCurrentFrame()
	window = frame.getContainerWindow()
	toolkit = window.getToolkit()
	msgbox = toolkit.createMessageBox(window, MESSAGEBOX, oBtnType, oTitle, oMessage)
	return msgbox.execute()
def oTest():
	try:
		cmd='mspaint.exe'
		oRtn = subprocess.call(cmd, shell=True)
		if oRtn != 0:
			oDisp = 'プロセスが異常終了しました'
			sys.exit()
		oDisp = str('Success')
	except Exception as er:
		oDisp = ''
		oDisp = str(traceback.format_exc()) + '\n' + str(er)
	finally:
		omsgbox(oDisp,1,'LO7.0.1.2')
#
# 参考URL : https://qiita.com/_akisato/items/d97b17064df158f0dea0

GSys-)[General]Windowsのプロセス一覧取得


#!
#coding: utf-8
# python Marco
import subprocess
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title'):
	"""shows message."""
	desktop = XSCRIPTCONTEXT.getDesktop()
	frame = desktop.getCurrentFrame()
	window = frame.getContainerWindow()
	toolkit = window.getToolkit()
	msgbox = toolkit.createMessageBox(window, MESSAGEBOX, oBtnType, oTitle, oMessage)
	return msgbox.execute()
def oTest():
	try:
		cmd = 'tasklist'
		proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
		oDisp1 = u'[Windowsのプロセス一覧1/4]'
		oDisp2 = u'[Windowsのプロセス一覧2/4]' + '\n'
		oDisp3 = u'[Windowsのプロセス一覧3/4]' + '\n'
		oDisp4 = u'[Windowsのプロセス一覧4/4]' + '\n'
		i = 0
		for line in proc.stdout:
			i = i + 1
			if i < 45:
				oDisp1 = oDisp1 + str(line.decode('utf-8', 'ignore'))
			elif i < 90:
				oDisp2 = oDisp2 + str(line.decode('utf-8', 'ignore'))
			elif i < 135:
				oDisp3 = oDisp3 + str(line.decode('utf-8', 'ignore'))
			else:
				oDisp4 = oDisp4 + str(line.decode('utf-8', 'ignore'))
		omsgbox(oDisp1,1,'LO7.0.1.2')
		omsgbox(oDisp2,1,'LO7.0.1.2')
		omsgbox(oDisp3,1,'LO7.0.1.2')
		omsgbox(oDisp4,1,'LO7.0.1.2')
		oDisp = 'Success'
	except Exception as e:
		oDisp = ''
		oDisp = str(traceback.format_exc()) + '\n' + str(er)
	finally:
		omsgbox(oDisp,1,'LO7.0.1.2')

GSys-)[General]





Windows API

GSys-)[General]MessageBoxW


#!
#coding: utf-8
# python Marco
from ctypes import *
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title'):
	"""shows message."""
	desktop = XSCRIPTCONTEXT.getDesktop()
	frame = desktop.getCurrentFrame()
	window = frame.getContainerWindow()
	toolkit = window.getToolkit()
	msgbox = toolkit.createMessageBox(window, MESSAGEBOX, oBtnType, oTitle, oMessage)
	return msgbox.execute()
def oTest():
	try:
		oUser32 = windll.user32
		oMessage = u'Hello World!!'
		oTitle = u'Python to Windows API'
		oUser32.MessageBoxW(0,oMessage,oTitle,0x00000040)
		oDisp = 'Success'
	except Exception as er:
		oDisp = ''
		oDisp = str(traceback.format_exc()) + '\n' + str(er)
	finally:
		omsgbox(oDisp,1,'LO7.0.1.2')
#
# MB_ICONINFORMATION (=0x00000040) 

GSys-)[General]表示中のウィンドウのタイトル一覧


#
#coding: utf-8
# python Marco
import ctypes
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
#
user32 = ctypes.WinDLL("user32")

EnumWindowsProc = ctypes.WINFUNCTYPE(ctypes.c_bool, ctypes.c_void_p, ctypes.c_void_p)

user32.EnumWindows.restype = ctypes.c_bool
user32.EnumWindows.argtypes = (EnumWindowsProc, ctypes.c_void_p)
user32.GetWindowTextW.restype = ctypes.c_int32
user32.GetWindowTextW.argtypes = (ctypes.c_void_p, ctypes.c_wchar_p, ctypes.c_int32)
oWinTitle = []
#
def omsgbox(oMessage='',oBtnType=1,oTitle='Title'):
	"""shows message."""
	desktop = XSCRIPTCONTEXT.getDesktop()
	frame = desktop.getCurrentFrame()
	window = frame.getContainerWindow()
	toolkit = window.getToolkit()
	msgbox = toolkit.createMessageBox(window, MESSAGEBOX, oBtnType, oTitle, oMessage)
	return msgbox.execute()
#
def callback(hWnd, lParam):
    windowText = ctypes.create_unicode_buffer(1024)
    user32.GetWindowTextW(hWnd, windowText, len(windowText))
    #可視化されたウィンドウかどうか
    if user32.IsWindowVisible(hWnd):
    	if windowText.value != '':
    		oTmp = str('{0:x}:\t {1}'.format(hWnd, windowText.value))
    		oWinTitle.append(oTmp)
    		return True
#
def oTest():
	try:
		user32.EnumWindows(EnumWindowsProc(callback), None)
		oDisp = '[表示中のウィンドウのタイトル一覧]\n ハンドル値:\t タイトル\n ----------------------------------------'
		for i in oWinTitle:
			oDisp = oDisp + '\n ' + str(i)
	except Exception as er:
		oDisp = ''
		oDisp = str(traceback.format_exc()) + '\n' + str(er)
	finally:
		omsgbox(oDisp,1,'LO7.0.1.2')
#
#俺言語 / 【Python】ウィンドウのタイトル文字列を取得する方法(win32api user32 GetWindowText)
#Qitta / Python: ctypesパターン集: コールバック関数
#上記はトップレベルウィンドウのみ。子ウィンドウを取得する時はEnumChildWindows() を利用すると良いみたい標準 Windows API / ウィンドウの列挙

GSys-)[General]











Network

GNet-)[General]siteのCharset取得


#!
#coding: utf-8
# python Marco
import urllib2
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title',oMsgType='messbox'):
	"""shows message."""
	desktop = XSCRIPTCONTEXT.getDesktop()
	frame = desktop.getCurrentFrame()
	window = frame.getContainerWindow()
	toolkit = window.getToolkit()
	msgbox = toolkit.createMessageBox(window, MESSAGEBOX, 1, 'Title', oMessage)
	return msgbox.execute()
def oTest():
	try:
		oURL = u'http://ja.libreoffice.org/'
		oOpenUrl = urllib2.urlopen(oURL)
		oCharset1 = oOpenUrl.info().get('content-type')
		oCharset2_0 = oOpenUrl.info().get('content-type', oCharset1).split(';')[0]
		oCharset2_1 = oOpenUrl.info().get('content-type', oCharset1).split(';')[1]
		oCharset3 = oOpenUrl.info().get('content-type', oCharset1).split('=')[1]
		#
		oOpenUrl.close()
		oDisp = u'[ URL / charset ]\n' + str(oCharset1) + '\n'\
		+ str(oCharset2_0) + '\n' + str(oCharset2_1) + '\n'\
		+ str(oCharset3)
	except:
		oDisp = traceback.format_exc(sys.exc_info()[2])
	finally:
		omsgbox(oDisp,1)
#
# [ 注意事項 ]
# 1) Python3系ではPython2系のurllibは廃止され、urllib2もurllib.requestという名称に変更されているらしい。

GNet-)[General]siteのSorce取得


#!
#coding: utf-8
# python Marco
#
import urllib.request	# 3.3
#import urllib			# 2.7
#
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title',oMsgType='messbox'):
	"""shows message."""
	desktop = XSCRIPTCONTEXT.getDesktop()
	frame = desktop.getCurrentFrame()
	window = frame.getContainerWindow()
	toolkit = window.getToolkit()
	msgbox = toolkit.createMessageBox(window, MESSAGEBOX, 1, 'Title', oMessage)
	return msgbox.execute()
def oTest():
	try:
		oURL = 'http://ja.libreoffice.org/'
		oOpenUrl = urllib.request.urlopen(oURL)	# 3.3
		#oOpenUrl = urllib.urlopen(oURL)		# 2.7
		#
		oUrlSrc = oOpenUrl.read()
		oDisp = oUrlSrc.decode('utf-8')
		#
		oOpenUrl.close()
	except Exception as er:
		oDisp = ''
		oDisp = str(traceback.format_exc()) + '\n' + str(er)
	finally:
		omsgbox(oDisp,1)
#
# [ 注意事項 ]
# 1) urllib2 moduleで行うとdecode変換Errorとなった。
# 2) urllibは読出し専用でしか開けません。またseek操作を行う事は出来ません。

GNet-)[General]URLからLocal Path取得


#!
#coding: utf-8
# python Marco
import urllib2
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title',oMsgType='messbox'):
	"""shows message."""
	desktop = XSCRIPTCONTEXT.getDesktop()
	frame = desktop.getCurrentFrame()
	window = frame.getContainerWindow()
	toolkit = window.getToolkit()
	msgbox = toolkit.createMessageBox(window, MESSAGEBOX, 1, 'Title', oMessage)
	return msgbox.execute()
def oTest():
	try:
		oURL = 'http://ja.libreoffice.org/'
		oLocalPath = urllib2.url2pathname(oURL)
		oDisp = u'[ URL => Local Path ]\n' + str(oURL) + '\n'\
		+ u' =>\n' + str(oLocalPath) 
	except:
		oDisp = traceback.format_exc(sys.exc_info()[2])
	finally:
		omsgbox(oDisp,1)

GNet-)[General]URI Encode/Decode


#!
#coding: utf-8
# python Marco
import urllib.request
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title',oMsgType='messbox'):
	"""shows message."""
	desktop = XSCRIPTCONTEXT.getDesktop()
	frame = desktop.getCurrentFrame()
	window = frame.getContainerWindow()
	toolkit = window.getToolkit()
	msgbox = toolkit.createMessageBox(window, MESSAGEBOX, 1, 'Title', oMessage)
	return msgbox.execute()
def Test():
	try:
		oEncoding = 'utf-8'
		oUrl = u'http://www.post.japanpost.jp/cgi-zip/zipcode.php?pref=13&city=1131010&id=45946'
		oUri_EnCd = urllib.request.quote(oUrl.encode(oEncoding))
		oUri_DeCd = urllib.request.unquote(oUri_EnCd)
		oDisp = oUrl + '\n  ↓\n [ URI Encode ]\n ' + str(oUri_EnCd) + '\n  ↓\n [ URI Decode ]\n ' + str(oUri_DeCd)
	except Exception as er:
		oDisp = ''
		oDisp = str(traceback.format_exc()) + '\n' + str(er)
	finally:
		omsgbox(oDisp,1)

GNet-)[General]HTTP Server(To be careful)

# MacroからHTTP Serverを起動させると言う「子亀が親亀をのせる」様な事はしないと思うが、忘備録として記す。
# 下記Codeを実行後にBrowserから「 http://127.0.0.1:8000 」を指定するとCurrent DirectoryのFile ListをBrowserに表示させる事が出来る。
# しかし、『PythonのThreadは外部からの強制停止ができない』のでHang状態になる。
# Pythonでは以下のKeyで強制終了可能な場合もあるらしいが、Macroでは無意味です。
# [ Net上での情報 ]
# Linux, Mac OS :[Ctrl]+[c]
# Windows  : [Ctrl]+[z](停止しないときはコンソールを閉じる)
# cmd.exe shellを使用時は[Ctrl]+[Break] (cmd.exe以外のShellを使っているとShellごと落ちる)
# 従って、下記Codeは取扱注意です。
#
********** [ Reference Code ] **********
#!
#coding: utf-8
# python Marco
import SimpleHTTPServer
import BaseHTTPServer
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title',oMsgType='messbox'):
	"""shows message."""
	desktop = XSCRIPTCONTEXT.getDesktop()
	frame = desktop.getCurrentFrame()
	window = frame.getContainerWindow()
	toolkit = window.getToolkit()
	msgbox = toolkit.createMessageBox(window, MESSAGEBOX, 1, 'Title', oMessage)
	return msgbox.execute()

def oTest():
	try:
		addr = ('127.0.0.1', 8000)
		Server = BaseHTTPServer.HTTPServer
		handler = SimpleHTTPServer.SimpleHTTPRequestHandler
		#
		httpd = Server(addr, handler)
		httpd.serve_forever()	# <= 待機し続ける状態になり終了出来くなる。/ httpd.handle_request()でも駄目
		#
	except:
		oDisp = traceback.format_exc(sys.exc_info()[2])
	finally:
		omsgbox(oDisp)

GNet-)[General]Web browser( Default browser )

#!
#coding: utf-8
# python Marco
import webbrowser
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title',oMsgType='messbox'):
	"""shows message."""
	desktop = XSCRIPTCONTEXT.getDesktop()
	frame = desktop.getCurrentFrame()
	window = frame.getContainerWindow()
	toolkit = window.getToolkit()
	msgbox = toolkit.createMessageBox(window, MESSAGEBOX, 1, 'Title', oMessage)
	return msgbox.execute()

def oTest():
	try:
		oURL = 'http://www.yahoo.co.jp/'
		if webbrowser.open(oURL,new=1,autoraise=1)== False:		# false is error
			raise webbrowser.Error
		oDisp = 'Success'
	except webbrowser.Error:
		oDisp = str(sys.stderr) + ' open failed'
	except:
		oDisp = traceback.format_exc(sys.exc_info()[2])
	finally:
		omsgbox(oDisp)
#
# ///// [ Option ] /////
# [ new ]
#  0 : 同じwindowでOpen
#  1 : 可能であればBrowserのnew windowでOpen
#  2 : 可能であればBrowserのnew TabでOpen
# [ autoraise ]
#  1 : open windowが前面
#  2 : open windowが後面(設定不可の場合がある。)

GNet-)[General]Web browser( Specified browser )

#!
#coding: utf-8
# python Marco
import webbrowser
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title',oMsgType='messbox'):
	"""shows message."""
	desktop = XSCRIPTCONTEXT.getDesktop()
	frame = desktop.getCurrentFrame()
	window = frame.getContainerWindow()
	toolkit = window.getToolkit()
	msgbox = toolkit.createMessageBox(window, MESSAGEBOX, 1, 'Title', oMessage)
	return msgbox.execute()
#
def oTest():
	try:
		oURL = 'http://www.yahoo.co.jp/'
		# Browser実行Fileの絶対Pathを「 " " 」間に記述
		browser = webbrowser.get('"c:\\Program Files\\Mozilla Firefox\\firefox.exe" %s')
		if browser.open(oURL)== False:		# false is error
			raise webbrowser.Error
		oDisp = 'Success'
	except webbrowser.Error:
		oDisp = str(sys.stderr) + ' open failed'
	except:
		oDisp = traceback.format_exc(sys.exc_info()[2])
	finally:
		omsgbox(oDisp)
#
# [ 注意 ]
# Optionを付けるとHang状態になる。

GNet-)[General]Web serverにあるfileをdownload


#!
#coding: utf-8
# python Marco
import urllib
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title',oMsgType='messbox'):
	"""shows message."""
	desktop = XSCRIPTCONTEXT.getDesktop()
	frame = desktop.getCurrentFrame()
	window = frame.getContainerWindow()
	toolkit = window.getToolkit()
	msgbox = toolkit.createMessageBox(window, MESSAGEBOX, 1, 'Title', oMessage)
	return msgbox.execute()
def oTest():
	try:
		oURL = 'http://ja.libreoffice.org/'
		oLocal = 'c:\\temp\\PythonMacroTest.html'
		urllib.urlretrieve(oURL , oLocal)
		oDisp = 'Success'
	except:
		oDisp = traceback.format_exc(sys.exc_info()[2])
	finally:
		omsgbox(oDisp,1)

GNet-)[General]IP Address、Host Name取得


#!
#coding: utf-8
# python Marco
import socket
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title'):
#	"""shows message."""
		desktop = XSCRIPTCONTEXT.getDesktop()
		frame = desktop.getCurrentFrame()
		window = frame.getContainerWindow()
		toolkit = window.getToolkit()
		msgbox = toolkit.createMessageBox(window, MESSAGEBOX, oBtnType, oTitle, oMessage)
		return msgbox.execute()
def oTest():
    try:
        host = socket.gethostname()
        ip = socket.gethostbyname(host)
        oDisp = 'Host Name : ' + str(host) + '\n\n' + 'IP Address : ' + str(ip)
    except Exception as er:
        oDisp = ''
        oDisp = str(traceback.format_exc()) + '\n' + str(er)
    finally:
        omsgbox(oDisp,1,'LO7.1.1.2(x64)')

GNet-)[General]





[ Google ]

GnGgle-)[General]YouTube

#!
#coding: utf-8
# python Marco
import webbrowser
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title',oMsgType='messbox'):
	"""shows message."""
	desktop = XSCRIPTCONTEXT.getDesktop()
	frame = desktop.getCurrentFrame()
	window = frame.getContainerWindow()
	toolkit = window.getToolkit()
	msgbox = toolkit.createMessageBox(window, MESSAGEBOX, 1, 'Title', oMessage)
	return msgbox.execute()

def oTest():
	try:
		oYouTubeId = 'sloEMUt7n5Q'
		oURL = 'http://www.youtube.com/watch?v=' + oYouTubeId
		if webbrowser.open(oURL,new=1,autoraise=1)== False:		# false is error
			raise webbrowser.Error
		oDisp = 'Success'
	except webbrowser.Error:
		oDisp = str(sys.stderr) + ' open failed'
	except:
		oDisp = traceback.format_exc(sys.exc_info()[2])
	finally:
		omsgbox(oDisp)

GnGgle-)[General]Google Mapから緯度/経度取得


#!
#coding: utf-8
# python Marco
import urllib.request
import xml.dom.minidom
import uno
import sys
import traceback
#
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title',oMsgType='messbox'):
	"""shows message."""
	desktop = XSCRIPTCONTEXT.getDesktop()
	frame = desktop.getCurrentFrame()
	window = frame.getContainerWindow()
	toolkit = window.getToolkit()
	msgbox = toolkit.createMessageBox(window, MESSAGEBOX, 1, 'Title', oMessage)
	return msgbox.execute()
def Test():
	try:
		oEncoding = 'utf-8'
		oAddr = u'東京都墨田区押上1-1-2'
		oUrl = u'http://maps.google.com/maps/api/geocode/xml?&language=ja&sensor=false&region=ja&address='	# ←regionの前の&は半角に変換する事
		oUrl = oUrl + urllib.request.quote(oAddr.encode(oEncoding))
		oBuffer = urllib.request.urlopen(oUrl).read()
		oDom = xml.dom.minidom.parseString(oBuffer)
		oLocation = oDom.getElementsByTagName('location')
		if oLocation.length > 0:
			oLatitude = oLocation[0].getElementsByTagName('lat')[0].firstChild.data
			oLongitude = oLocation[0].getElementsByTagName('lng')[0].firstChild.data
			oDisp = u'[ 世界測地系 ]\n' + oAddr + '\n' + u'(東京スカイツリー)' + '\n → \n' + u'緯度 = '\
			+ str(oLatitude) + '\n' + u'経度 = ' + str(oLongitude)
		else:
			oDisp = u'緯度/経度の取得に失敗しました。'
	except Exception as er:
		oDisp = ''
		oDisp = str(traceback.format_exc()) + '\n' + str(er)
	finally:
		omsgbox(oDisp,1)
#
# 緯度/経度の取得は「キウイと鳴くからキウイフルーツ/pythonでgoogle mapを弄る」のPageを参照させて頂きました。
# 上記Pageに記されている様に、JSON形式での取得の場合、/xml? → /json? にすれば良いらしい。
# 緯度/経度の確認は「knecht api」のSiteを利用させて頂きました。

GnGgle-)[General]Google Mapから緯度/経度取得(JSON)


#!
#coding: utf-8
# python Marco
import urllib.request
import json
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
#
class DictObj(dict):
	__getattr__ = dict.__getitem__ 
#
def omsgbox(oMessage='',oBtnType=1,oTitle='Title',oMsgType='messbox'):
	"""shows message."""
	desktop = XSCRIPTCONTEXT.getDesktop()
	frame = desktop.getCurrentFrame()
	window = frame.getContainerWindow()
	toolkit = window.getToolkit()
	msgbox = toolkit.createMessageBox(window, MESSAGEBOX, 1, 'Title', oMessage)
	return msgbox.execute()
def Test():
	try:
		oEncoding = 'utf-8'
		oAddr = u'東京都墨田区押上1-1-2'
		oUrl = u'http://maps.google.com/maps/api/geocode/json?&language=ja&sensor=false&region=ja&address='	# ←regionの前の&は半角に変換する事
		oUrl = oUrl + urllib.request.quote(oAddr.encode(oEncoding))
		oBuffer = urllib.request.urlopen(oUrl).read()
		# JSON DataをDictionanry typeへ変換
		oDict = json.loads(str(oBuffer.decode(oEncoding)),object_hook=DictObj)
		oStatus = oDict['status']
		if oStatus == 'OK':
			oDict2 = oDict['results']
			oLatitude = oDict2[0].geometry.location.lat
			oLongitude = oDict2[0].geometry.location.lng
			oDisp = u'[ Google Map/JSON ]\n\n' + oAddr + '\n' + u'(東京スカイツリー)' + '\n → \n' + u'緯度 = '\
			+ str(oLatitude) + '\n' + u'経度 = ' + str(oLongitude)
		else:
			oDisp = u'Dataの取得に失敗しました。'
	except Exception as er:
		oDisp = ''
		oDisp = str(traceback.format_exc()) + '\n' + str(er)
	finally:
		omsgbox(oDisp,1)
#
# [ Note ]
# oDisp = str(oDict) とすると Google GeometoryのReturn項目全てが確認出来る(と思う?)。
#
# [ Reference Site ]
# 1) Google Geocoding API(JSON 出力形式)
# 2) Google Maps API ウェブ サービス(Javascript による JSON の処理)
# 3) CMLog(Python3でsimplejson?)
# 4) Keep on moving / 辞書にオブジェクトっぽくアクセスする

GnGgle-)[General]Google Mapから緯度/経度取得( JSON表示 )


#!
#coding: utf-8
# python Marco
import urllib.request
import json
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title',oMsgType='messbox'):
	"""shows message."""
	desktop = XSCRIPTCONTEXT.getDesktop()
	frame = desktop.getCurrentFrame()
	window = frame.getContainerWindow()
	toolkit = window.getToolkit()
	msgbox = toolkit.createMessageBox(window, MESSAGEBOX, 1, 'Title', oMessage)
	return msgbox.execute()
def Test():
	try:
		oEncoding = 'utf-8'
		oAddr = u'東京都墨田区押上1-1-2'
		oUrl = u'http://maps.google.com/maps/api/geocode/json?&language=ja&sensor=false&region=ja&address='		# ←regionの前の&は半角に変換する事
		oUrl = oUrl + urllib.request.quote(oAddr.encode(oEncoding))
		oBuffer = urllib.request.urlopen(oUrl).read()
		oJson = json.loads(oBuffer.decode(oEncoding))
		oDom = json.dumps([s1['geometry'] for s1 in oJson['results']],indent=2)	# 階層に2space分のindentを付ける。省略するとindent無し( =0 )
		oDisp = oDom
	except Exception as er:
		oDisp = ''
		oDisp = str(traceback.format_exc()) + '\n' + str(er)
	finally:
		omsgbox(oDisp,1)

GnGgle-)[General]緯度/経度からAddress取得/Reverse geocoding(XML)


#!
#coding: utf-8
# python Marco
import urllib.request
import xml.dom.minidom
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title',oMsgType='messbox'):
	"""shows message."""
	desktop = XSCRIPTCONTEXT.getDesktop()
	frame = desktop.getCurrentFrame()
	window = frame.getContainerWindow()
	toolkit = window.getToolkit()
	msgbox = toolkit.createMessageBox(window, MESSAGEBOX, 1, 'Title', oMessage)
	return msgbox.execute()
def Test():
	try:
		oEncoding = 'utf-8'
		oLat = u'35.7100327'
		oLng = u'139.8107155'
		oUrl = u'http://maps.google.com/maps/api/geocode/xml?latlng=' + oLat + u',' + oLng + u'&sensor=false'
		oBuffer = urllib.request.urlopen(oUrl).read()
		oDom = xml.dom.minidom.parseString(oBuffer)
		oStatus = oDom.getElementsByTagName('GeocodeResponse')[0].getElementsByTagName('status')[0].firstChild.data
		if oStatus == 'OK':
			oResult = oDom.getElementsByTagName('result')
			oAddress = oResult[0].getElementsByTagName('formatted_address')[0].firstChild.data
			oDisp = u'[ 緯度 = ' + str(oLat) + u' / 経度 = ' + str(oLng) + ' ]\n' + str(oAddress) 
		else:
			oDisp = u'Addressの取得に失敗しました。'
	except Exception as er:
		oDisp = ''
		oDisp = str(traceback.format_exc()) + '\n' + str(er)
	finally:
		omsgbox(oDisp,1)

GnGgle-)[General]緯度/経度からAddress取得/Reverse geocoding(JSON)


#!
#coding: utf-8
# python Marco
import urllib.request
import json
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
#
class DictObj(dict):
	__getattr__ = dict.__getitem__ 
#
def omsgbox(oMessage='',oBtnType=1,oTitle='Title',MsgType=MESSAGEBOX):
#	"""shows message."""
		desktop = XSCRIPTCONTEXT.getDesktop()
		frame = desktop.getCurrentFrame()
		window = frame.getContainerWindow()
		toolkit = window.getToolkit()
		msgbox = toolkit.createMessageBox(window, MsgType, oBtnType, oTitle, oMessage)
		return msgbox.execute()
def Test():
	try:
		oEncoding = 'utf-8'
		oLat = u'35.7100327'
		oLng = u'139.8107155'
		oUrl = u'http://maps.google.com/maps/api/geocode/json?latlng=' + oLat + u',' + oLng + u'&sensor=false'
		oBuffer = urllib.request.urlopen(oUrl).read()
		# JSON DataをDictionanry typeへ変換
		oDict = json.loads(str(oBuffer.decode(oEncoding)),object_hook=DictObj)
		oStatus = oDict['status']
		if oStatus == 'OK':
			oDict2 = oDict['results']
			oGou = oDict2[0].address_components[0].short_name
			oBanchi = oDict2[0].address_components[1].short_name
			oChou = oDict2[0].address_components[2].short_name
			oCity2 = oDict2[0].address_components[3].short_name
			oCity1 = oDict2[0].address_components[4].short_name
			oPref = oDict2[0].address_components[5].short_name
			oCountry = oDict2[0].address_components[6].short_name
			oDisp = u'[ Google Map/JSON ]\n' + u'(Address of TOKYO SKYTREE)\n → '\
			+ str(oGou) + ',' + str(oBanchi) + ',' + str(oChou) + ',' + str(oCity2)\
			+ ',' + str(oCity1) + ',' + str(oPref) + ',' + str(oCountry)
		else:
			oDisp = u'Addressの取得に失敗しました。'
	except Exception as er:
		oDisp = ''
		oDisp = str(traceback.format_exc()) + '\n' + str(er)
	finally:
		omsgbox(oDisp,1)

GnGgle-)[General]緯度/経度からAddress取得/Reverse geocoding( JSON表示 )


#!
#coding: utf-8
# python Marco
import urllib.request
import json
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
#
class DictObj(dict):
	__getattr__ = dict.__getitem__ 
#
def omsgbox(oMessage='',oBtnType=1,oTitle='Title',MsgType=MESSAGEBOX):
#	"""shows message."""
		desktop = XSCRIPTCONTEXT.getDesktop()
		frame = desktop.getCurrentFrame()
		window = frame.getContainerWindow()
		toolkit = window.getToolkit()
		msgbox = toolkit.createMessageBox(window, MsgType, oBtnType, oTitle, oMessage)
		return msgbox.execute()
def Test():
	try:
		oEncoding = 'utf-8'
		oLat = u'35.7100327'
		oLng = u'139.8107155'
		oUrl = u'http://maps.google.com/maps/api/geocode/json?latlng=' + oLat + u',' + oLng + u'&sensor=false'
		oBuffer = urllib.request.urlopen(oUrl).read()
		# JSON DataをDictionanry typeへ変換
		oJson = json.loads(oBuffer.decode(oEncoding))
		oDom = json.dumps([s1['address_components'] for s1 in oJson['results']],indent=2)
		oDisp = oDom
	except Exception as er:
		oDisp = ''
		oDisp = str(traceback.format_exc()) + '\n' + str(er)
	finally:
		omsgbox(oDisp,1)

GnGgle-)[General]Google map / Route検索(XML)


#!
#coding: utf-8
# python Marco
import urllib.request
import xml.dom.minidom
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title',MsgType=MESSAGEBOX):
#	"""shows message."""
		desktop = XSCRIPTCONTEXT.getDesktop()
		frame = desktop.getCurrentFrame()
		window = frame.getContainerWindow()
		toolkit = window.getToolkit()
		msgbox = toolkit.createMessageBox(window, MsgType, oBtnType, oTitle, oMessage)
		return msgbox.execute()
def Test():
	try:
		oEncoding = 'utf-8'
		oStart = u'東京都新宿区新宿三丁目38-1'	# JR新宿駅西口
		oEnd = u'東京都新宿区西新宿2-8-1'	# 東京都庁
		oMode = 'walking'
		oUrl = u'http://maps.googleapis.com/maps/api/directions/xml?origin='
		oUrl = oUrl + urllib.request.quote(oStart.encode(oEncoding)) + '&destination='\
			+ urllib.request.quote(oEnd.encode(oEncoding)) + '&sensor=false&mode=' + oMode
		oBuffer = urllib.request.urlopen(oUrl).read()
		oDom = xml.dom.minidom.parseString(oBuffer)
		oStatus = oDom.getElementsByTagName('status')[0].firstChild.data
		if oStatus == 'OK':
			oRoute = oDom.getElementsByTagName('route')
			# oSummary = oRoute[0].getElementsByTagName('summary')[0].firstChild.data	# ← Errorになる。
			oSummary = 'Route'
			oLeg = oRoute[0].getElementsByTagName('leg')
			oDistance = oLeg[0].getElementsByTagName('distance')[7].getElementsByTagName('text')[0].firstChild.data
			oTime = oLeg[0].getElementsByTagName('duration')[7].getElementsByTagName('text')[0].firstChild.data
			oDisp = oDistance + ', ' + oTime + '\n\n [ ' + oSummary + ' ]'
			for oSp in range(7):
				oStepIct = oLeg[0].getElementsByTagName('step')[oSp].getElementsByTagName('html_instructions')[0].firstChild.data
				oStepDtc = oLeg[0].getElementsByTagName('step')[oSp].getElementsByTagName('distance')[0].getElementsByTagName('text')[0].firstChild.data
				oStepTm = oLeg[0].getElementsByTagName('step')[oSp].getElementsByTagName('duration')[0].getElementsByTagName('text')[0].firstChild.data
				oNo = oSp + 1
				oDisp = oDisp + '\n' + str(oNo) + ' : ' + oStepIct + ' / ' + oStepDtc + '( ' + oStepTm + ' )'
		else:
			oDisp = u'Route取得に失敗しました。'
	except Exception as er:
		oDisp = ''
		oDisp = str(traceback.format_exc()) + '\n' + str(er)
	finally:
		omsgbox(oDisp,1)
#
# [ Note ]
# 交通手段は driving, walkingのみ。bicycling, transitを指定するとReturn Error( Status = INVALID_REQUEST: 指定されたリクエストが無効であることを示します。 )

GnGgle-)[General]Google map / Route検索(JSON)


#!
#coding: utf-8
# python Marco
import urllib.request
import json
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
#
class DictObj(dict):
	__getattr__ = dict.__getitem__ 
#
def omsgbox(oMessage='',oBtnType=1,oTitle='Title',MsgType=MESSAGEBOX):
#	"""shows message."""
		desktop = XSCRIPTCONTEXT.getDesktop()
		frame = desktop.getCurrentFrame()
		window = frame.getContainerWindow()
		toolkit = window.getToolkit()
		msgbox = toolkit.createMessageBox(window, MsgType, oBtnType, oTitle, oMessage)
		return msgbox.execute()
def Test():
	try:
		oEncoding = 'utf-8'
		oStart = u'東京都新宿区新宿三丁目38-1'	# JR新宿駅西口
		oEnd = u'東京都新宿区西新宿2-8-1'	# 東京都庁
		oMode = 'walking'
		# 
		oUrl = u'http://maps.googleapis.com/maps/api/directions/json?origin='
		oUrl = oUrl + urllib.request.quote(oStart.encode(oEncoding)) + '&destination='\
			+ urllib.request.quote(oEnd.encode(oEncoding)) + '&sensor=false&mode=' + oMode
		oBuffer = urllib.request.urlopen(oUrl).read()
		# JSON DataをDictionanry typeへ変換
		oDict = json.loads(str(oBuffer.decode(oEncoding)),object_hook=DictObj)
		oDict2 = oDict['routes']
		oDistance = oDict2[0].legs[0].distance.text
		oTime = oDict2[0].legs[0].duration.text
		oDisp = oDistance + ', ' + oTime
		# Step(道順)
		for oSp in range(7):
			oStepIct = oDict2[0].legs[0].steps[oSp].html_instructions
			oStepDtc = oDict2[0].legs[0].steps[oSp].distance.text
			#oStepTm = oDict2[0].legs[0].steps[oSp].duration.text
			oNo = oSp + 1
			oDisp = oDisp + '\n' + str(oNo) + ' : ' + oStepIct + ' / ' + oStepDtc
	except Exception as er:
		oDisp = ''
		oDisp = str(traceback.format_exc()) + '\n' + str(er)
	finally:
		omsgbox(oDisp,1)
#
# [ Note ]
# Refet site : Google Directions API

GnGgle-)[General]( Old )Google Stock(XML)


#!
#coding: utf-8
# python Marco
import urllib.request
import xml.dom.minidom
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title',MsgType=MESSAGEBOX):
#	"""shows message."""
		desktop = XSCRIPTCONTEXT.getDesktop()
		frame = desktop.getCurrentFrame()
		window = frame.getContainerWindow()
		toolkit = window.getToolkit()
		msgbox = toolkit.createMessageBox(window, MsgType, oBtnType, oTitle, oMessage)
		return msgbox.execute()
def Test():
	try:
		oSymbol = u'6758'
		oUrl = u'http://www.google.co.jp/ig/api?stock=' + oSymbol
		oOpen = urllib.request.urlopen(oUrl)
		oCharset = oOpen.info().get('content-type')
		oEncoding = oOpen.info().get('content-type', oCharset).split('=')[1]
		oBuffer = oOpen.read()
		oDecode = str(oBuffer.decode(oEncoding))
		oDom = xml.dom.minidom.parseString(oDecode)
		oComyChk = oDom.getElementsByTagName('company')
		if oComyChk.length > 0:
			oComy = oDom.getElementsByTagName('company')[0].attributes['data'].value
			oCmySymbol = oDom.getElementsByTagName('symbol')[0].attributes['data'].value
			oMarket = oDom.getElementsByTagName('exchange')[0].attributes['data'].value
			oCurcy = oDom.getElementsByTagName('currency')[0].attributes['data'].value
			oStock = oDom.getElementsByTagName('last')[0].attributes['data'].value
			oHigh = oDom.getElementsByTagName('high')[0].attributes['data'].value
			oLow = oDom.getElementsByTagName('low')[0].attributes['data'].value
			oDiff = oDom.getElementsByTagName('change')[0].attributes['data'].value
			oDate = oDom.getElementsByTagName('current_date_utc')[0].attributes['data'].value
			oTime = oDom.getElementsByTagName('current_time_utc')[0].attributes['data'].value 
			oDisp = '[ Google Stock ]\n Date Time\t : ' + str(oDate) + '( ' + str(oTime) + ' )'
			oDisp = oDisp + '\n Campany\t : ' + str(oComy) +'\n Symbol\t\t : ' + str(oCmySymbol) + '\n Market\t\t : ' + str(oMarket)
			oDisp = oDisp + '\n Currency\t : ' + str(oCurcy) + '\n Value\t\t\t : ' + str(oStock) + '(' + str(oDiff) + ')' 
			oDisp = oDisp + '\n High / Low\t : ' + str(oHigh) + ' / ' + str(oLow)
		else:
			oDisp = u'Stock Dataの取得に失敗しました。'
	except Exception as er:
		oDisp = ''
		oDisp = str(traceback.format_exc()) + '\n' + str(er)
	finally:
		omsgbox(oDisp,1)
#
# [ Note ]
# Finance Service終了した模様。
# # Tokyo in Japan   : oCode = Stock Code / u'http://www.google.co.jp/ig/api?stock='
# New York in USA  : oCode = Ticker Symbol / u'http://www.google.com/ig/api?stock='
# Frankfurt or Euronext Brussels in Germany : oCode = Symbol / u'http://www.google.de/ig/api?stock='
# { Market Symbol } # TYO : Tokyo / NYSE : New York / Nasdaq : Nasdaq / BIT : Frankfurt or Euronext Brussels? # Decodeしないと USA 以外はXML取得に失敗する。

GnGgle-)[General]( Old )Google Currency Converter


#!
#coding: utf-8
# python Marco
import urllib.request
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title',MsgType=MESSAGEBOX):
#	"""shows message."""
		desktop = XSCRIPTCONTEXT.getDesktop()
		frame = desktop.getCurrentFrame()
		window = frame.getContainerWindow()
		toolkit = window.getToolkit()
		msgbox = toolkit.createMessageBox(window, MsgType, oBtnType, oTitle, oMessage)
		return msgbox.execute()
def Test():
	try:
		oCurrency = u'USD'
		oExchange = u'JPY'
		oUrl = u'http://www.google.com/ig/calculator?hl=en&q=1' + oCurrency + '=?' + oExchange
		oBuffer = urllib.request.urlopen(oUrl).read()
		# Create Dictionary with Retuen( String ) from URL
		oBufStr = str(oBuffer)
		oLen = len(oBufStr)
		oData = oBufStr[3:oLen-2]
		oSplit = oData.split(',')
		oDict = {}
		for oElm in oSplit:
			oUnit = oElm.split(':')
			oKey = str(oUnit[0])
			oVal = oUnit[1].replace('"','')
			oDict[oKey] = oVal
		if oDict['error'] != '':
			oCurVal = oDict['lhs']
			oExcVal = oDict['rhs']
			oDisp = u'[ Google Currency Coverter ]\n' + oCurVal + '\n\t ↑ ↓ \n' + oExcVal
		else:
			oDisp = u'Dataの取得に失敗しました。'
	except Exception as er:
		oDisp = ''
		oDisp = str(traceback.format_exc()) + '\n' + str(er)
	finally:
		omsgbox(oDisp,1)
#
# [ Note ]
# Cuurncy Symbol / 取得出来ない通貨(ex. Iran Rial)もある。
# Refer site : Stockoverflow / how do I get currency exchange rates using Google Finance API

GnGgle-)[General]Google Time Zone(JSON)


#!
#coding: utf-8
# python Marco
import urllib.request
import json
import datetime, calendar
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
#
class DictObj(dict):
	__getattr__ = dict.__getitem__ 
#
def omsgbox(oMessage='',oBtnType=1,oTitle='Title',MsgType=MESSAGEBOX):
#	"""shows message."""
		desktop = XSCRIPTCONTEXT.getDesktop()
		frame = desktop.getCurrentFrame()
		window = frame.getContainerWindow()
		toolkit = window.getToolkit()
		msgbox = toolkit.createMessageBox(window, MsgType, oBtnType, oTitle, oMessage)
		return msgbox.execute()
def Test():
	try:
		oEncoding = 'utf-8'
		# 緯度、経度取得
		oAddr = u'東京都'
		oUrl = u'http://maps.google.com/maps/api/geocode/json?&language=ja&sensor=false' + '&' + 'region=ja&address='	# ←regionの前の&は半角に変換する事(必須)
		oUrl = oUrl + urllib.request.quote(oAddr.encode(oEncoding))
		oBuffer = urllib.request.urlopen(oUrl).read()
		oDict = json.loads(str(oBuffer.decode(oEncoding)),object_hook=DictObj)
		oStatus = oDict['status']
		if oStatus == 'OK':
			oDict2 = oDict['results']
			oLatitude = oDict2[0].geometry.location.lat
			oLongitude = oDict2[0].geometry.location.lng
		else:
			oDisp = u'緯度、経度Dataの取得に失敗しました。'
		# UTC Stime Stamp
		oUtcTime = datetime.datetime.utcnow()
		oTimeStamp = calendar.timegm(oUtcTime.timetuple())
		# Time Zone取得
		oUrl=''; oBuffer=''; oDict = ''; oStatus = ''	# 念の為に初期化
		oUrl ='https://maps.googleapis.com/maps/api/timezone/json?location='
		oUrl =oUrl + str(oLatitude) + ',' + str(oLongitude) + '&' + 'timestamp=' + str(oTimeStamp) + '&sensor=false'	# ←timestampの前の&は半角に変換する事(必須)
		oBuffer = urllib.request.urlopen(oUrl).read()
		oDict = json.loads(str(oBuffer.decode(oEncoding)),object_hook=DictObj)
		oStatus = oDict['status']
		if oStatus == 'OK':
			oDateDiff = oDict['dstOffset']
			oTimeDiff = oDict['rawOffset']
			oZoneId = oDict['timeZoneId']
			oZoneName = oDict['timeZoneName']
			oDisp = u'[ Google Time Zone ]\n 協定世界時(UTC)\n → ' + str(oUtcTime) + '\n Date差 = ' + str(oDateDiff) + u' [ days ]\n 協定世界時(UTC)との差 = '\
			+ str(oTimeDiff) + u'[ sec ]\n Zome Id = ' + str(oZoneId) + u'\n Zome Name = ' + str(oZoneName)
		else:
			oDisp = u'Time Zone Dataの取得に失敗しました。'
	except Exception as er:
		oDisp = ''
		oDisp = str(traceback.format_exc()) + '\n' + str(er)
	finally:
		omsgbox(oDisp,1)
#
# [ Note ]
# The Google Time Zone API
# 協定世界時(UTC)

GnGgle-)[General]Google Translateを使って文字発音( Only Windows )

#!
#coding: utf-8
# python Marco
import time
import uno
import sys, traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title',MsgType=MESSAGEBOX):
#	"""shows message."""
		desktop = XSCRIPTCONTEXT.getDesktop()
		frame = desktop.getCurrentFrame()
		window = frame.getContainerWindow()
		toolkit = window.getToolkit()
		msgbox = toolkit.createMessageBox(window, MsgType, oBtnType, oTitle, oMessage)
		return msgbox.execute()
def createUnoService(service_name):
	"""Create a UNO Service By this name"""
	ctx = XSCRIPTCONTEXT.getComponentContext()
	try:
		service = ctx.ServiceManager.createInstanceWithContext(service_name, ctx)
	except:
		service = NONE
	return service
def Test():
	try:
		oWord = []
		oWord.append('Japan')
		oWord.append('Apache OpenOffice')
		oWord.append('LibreOffice')
		oDisp = ''
		for w in oWord:
			if w.strip() != '':
				oGoogleURL = 'http://translate.google.com/translate_tts?tl=en&q=' + str(w)
				oMediaDirectX = createUnoService('com.sun.star.media.Manager_DirectX')
				oPlayer =  oMediaDirectX.createPlayer(oGoogleURL)
				oPlayer.start()
				m = 1
				while oPlayer.MediaTime < oPlayer.Duration and m < 10000:
				# while oPlayer.MediaTime < oPlayer.StopTime and m < 10000:
					time.sleep(0.5)		# 0.5 [sec]
					m=m+1
		oDisp = 'Success'
	except Exception as er:
		oDisp = ''
		oDisp = str(traceback.format_exc()) + '\n' + str(er)
	finally:
		omsgbox(oDisp,1)
#
# [ Note ]
# 1) Windows DirectX機能を利用しているので、Windows環境で動作します。
# 2) LibreOffice 4系では Duration : ○ / StopTime:× の模様

GnGgle-)[General]





[ Other ]

GnNetOtr-)[General]O'Reilly Japan Ebook Storeから書籍情報取得


#!
#coding: utf-8
# python Marco
import urllib.request
import json
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
#
class DictObj(dict):
	__getattr__ = dict.__getitem__ 
#
def omsgbox(oMessage='',oBtnType=1,oTitle='Title',MsgType=MESSAGEBOX):
#	"""shows message."""
		desktop = XSCRIPTCONTEXT.getDesktop()
		frame = desktop.getCurrentFrame()
		window = frame.getContainerWindow()
		toolkit = window.getToolkit()
		msgbox = toolkit.createMessageBox(window, MsgType, oBtnType, oTitle, oMessage)
		return msgbox.execute()
def Test():
	try:
		oEncoding = 'utf-8'
		oISBN = u'4873111773'
		oUrl = u'http://www.oreilly.co.jp/books/' + oISBN + '/biblio.json'
		oBuffer = urllib.request.urlopen(oUrl).read()
		oDict = json.loads(str(oBuffer.decode(oEncoding)),object_hook=DictObj)
		oTitle = oDict['title']
		oAuth = oDict['authors']
		oRelease = oDict['released']
		oPage = oDict['pages']
		oPrice = oDict['price']
		oDisp = u'[ O\'Reilly Book ]\n Title\t\t : ' + str(oTitle) + '\n Author\t  : ' + str(oAuth) + '\n Release\t : ' + str(oRelease)\
			+ '\n Page\t\t : ' + str(oPage) + '\n Price\t\t : ' + str(oPrice)
	except Exception as er:
		oDisp = ''
		oDisp = str(traceback.format_exc()) + '\n' + str(er)
	finally:
		omsgbox(oDisp,1)
#
#[ Note ]
# Refer Site : O'Reilly Japan / JSON形式による書誌情報の提供をはじめました
# ISBN は O'Reilly Japan Ebook Store の13桁のISBNを用いる事。O'Reilly Japan Ebook Storeで扱っていないISBNはError。

GnNetOtr-)[General]国立国会図書館Search


#!
#coding: utf-8
# python Marco
import urllib.request
import xml.etree.ElementTree as oTr
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title',MsgType=MESSAGEBOX):
#	"""shows message."""
		desktop = XSCRIPTCONTEXT.getDesktop()
		frame = desktop.getCurrentFrame()
		window = frame.getContainerWindow()
		toolkit = window.getToolkit()
		msgbox = toolkit.createMessageBox(window, MsgType, oBtnType, oTitle, oMessage)
		return msgbox.execute()
def Test():
	try:
		oEncoding = 'utf-8'
		oKeyword = u'title=LibreOffice'
		oFrom = u'from=2012'
		oTmpQuery = oKeyword +' AND ' + oFrom
		oQuery = urllib.request.quote(oTmpQuery.encode(oEncoding))
		oUrl = u'http://iss.ndl.go.jp/api/sru?operation=searchRetrieve&query=' + oQuery
		oBuffer = urllib.request.urlopen(oUrl).read()
		root = oTr.fromstring(oBuffer)
		oRecs = root.findall('{http://www.loc.gov/zing/srw/}records')
		oRec = oRecs[0].findall('{http://www.loc.gov/zing/srw/}record')
		oNum = len(oRec)
		if oNum != 0:
			oDisp = u'[ 国立国会図書館 API ]'
			for oS in range(oNum):
				oRecData = oRec[oS].findall('{http://www.loc.gov/zing/srw/}recordData')
				# recordData Tagの子は文字列の模様
				oText = oRecData[0].text
				oTitleTop = oText.find('')
				oTitleEnd  = oText.find('')
				oTitle = oText[oTitleTop+10:oTitleEnd]
				oAuthTop = oText.find('')
				oAuthEnd  = oText.find('')
				oAuthor = oText[oAuthTop+12:oAuthEnd]
				oPubhTop = oText.find('')
				oPubhEnd  = oText.find('')
				oPublish = oText[oPubhTop+14:oPubhEnd]
				oDisp = oDisp + u'\n検索結果(' + str(oS+1) + ')\n' + oTitle + '\n' + oAuthor + '\n' + oPublish + '\n'
		else:
			oDisp = u' 該当する図書が無いか \n Dataの取得に失敗しました'
	except Exception as er:
		oDisp = ''
		oDisp = str(traceback.format_exc()) + '\n' + str(er)
	finally:
		omsgbox(oDisp,1)
# [ Note ]
# 国立国会図書館サーチ/外部提供インタフェース(API)
# Refer Site : Dive Into Python 3 / XML ( Japanease / English )
# ( 注意!! ) # 期間( FROM )やKeywordを汎用句を用いると処理時間が非常に掛かる事ので注意!!

GnNetOtr-)[General]Stock Price Data from Bloomberg


#!
#coding: utf-8
# python Marco
import urllib.request
import json
import uno
import sys, traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
#
class DictObj(dict):
	__getattr__ = dict.__getitem__ 
#
def omsgbox(oMessage='',oBtnType=1,oTitle='Title',MsgType=MESSAGEBOX):
#	"""shows message."""
		desktop = XSCRIPTCONTEXT.getDesktop()
		frame = desktop.getCurrentFrame()
		window = frame.getContainerWindow()
		toolkit = window.getToolkit()
		msgbox = toolkit.createMessageBox(window, MsgType, oBtnType, oTitle, oMessage)
		return msgbox.execute()
def Test():
	try:
		oEncoding = 'utf-8'
		oSymbol = '6758:JP'
		#oSymbol = 'AAPL:US'
		oUrl = 'http://www.bloomberg.com/markets/watchlist/recent-ticker/'
		oUrl = oUrl + oSymbol
		oBuffer = urllib.request.urlopen(oUrl).read()
		# JSON DataをDictionanry typeへ変換
		oDict = json.loads(str(oBuffer.decode(oEncoding)),object_hook=DictObj)
		oRtnChk = oDict['return_code']
		if oRtnChk == 0:
			oCmpyName = oDict['disp_name']		# Company name
			oPrice = oDict['last_price']		# Stock price
			oRate = oDict['pct_chge_1D']		# Previous day rate
			oTime = oDict['time_of_last_updt']	# Company name
			oDisp = u'[ 株価(bloomberg) ]\n\t Company Name : ' + str(oCmpyName) + '\n\t Stock Price \t: ' + str(oPrice)\
			+ u'円\n\t 前日比 \t\t: ' + str(oRate) + u'%\n\t 更新時間 \t: ' + str(oTime)
		else:
			oDisp = u'Data取得に失敗しました'
	except Exception as er:
		oDisp = ''
		oDisp = str(traceback.format_exc()) + '\n' + str(er)
	finally:
		omsgbox(oDisp,1)
#
# [ Note ]
# Bloomberg
# Japan : 証券Code:JP / USA : Ticker Symbol:US

GnNetOtr-)[General]











Regular Expression( 正規表現 )

GReEp-)[General]該当する検索文字を全て取得


#!
#coding: utf-8
# python Marco
import re
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title',MsgType=MESSAGEBOX):
#	"""shows message."""
		desktop = XSCRIPTCONTEXT.getDesktop()
		frame = desktop.getCurrentFrame()
		window = frame.getContainerWindow()
		toolkit = window.getToolkit()
		msgbox = toolkit.createMessageBox(window, MsgType, oBtnType, oTitle, oMessage)
		return msgbox.execute()
def oTest():
	try:
		oStr = 'Which foot or hand fell fastest'
		oReEp = re.findall(r'\bf[a-z]*',oStr)		# fから始まる文字の検索
		oDisp = u'[ 正規表現 ]\n'\
		+ 're.findall(r\'\\bf[a-z]*\',' + oStr + ')\n => '\
		+ str(oReEp)
	except:
		oDisp = traceback.format_exc(sys.exc_info()[2])
	finally:
		omsgbox(oDisp,1)

GReEp-)[General]重複しないmatchの中で一番左の値を置換


#!
#coding: utf-8
# python Marco
import re
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title',MsgType=MESSAGEBOX):
#	"""shows message."""
		desktop = XSCRIPTCONTEXT.getDesktop()
		frame = desktop.getCurrentFrame()
		window = frame.getContainerWindow()
		toolkit = window.getToolkit()
		msgbox = toolkit.createMessageBox(window, MsgType, oBtnType, oTitle, oMessage)
		return msgbox.execute()
def oTest():
	try:
		oStr = 'cat cat in in the hat hat'
		# re.sub(pattern, repl, string[, count])
		# string 内で、 pattern と重複しないマッチの内、一番左にあるものを置換 repl で置換して得られた文字列を返します。
		# もしパターンが見つからなければ、 string を変更せずに返します。 
		oReEp = re.sub(r'(\b[a-z]+) \1',r'\1',oStr)
		oDisp = u'[ 正規表現 ]\n'\
		+ 're.sub(r\'(\\b[a-z]+) \\1\',r\'\\1\',' + oStr + ')\n => '\
		+ str(oReEp)
	except:
		oDisp = traceback.format_exc(sys.exc_info()[2])
	finally:
		omsgbox(oDisp,1)

GReEp-)[General]正規表現で文字列を分割


#!
#coding: utf-8
# python Marco
import re
import os
import uno
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title',MsgType=MESSAGEBOX):
#	"""shows message."""
		desktop = XSCRIPTCONTEXT.getDesktop()
		frame = desktop.getCurrentFrame()
		window = frame.getContainerWindow()
		toolkit = window.getToolkit()
		msgbox = toolkit.createMessageBox(window, MsgType, oBtnType, oTitle, oMessage)
		return msgbox.execute()
def oTest():
	try:
		oResult = re.split('[ceg]', 'abcdefghi')
		oDisp = u'[ 正規表現で文字列を分割 ]\n' + 're.split(''[ceg]'', ''abcdefghi'')\n = ' + str(oResult)
	except:
		oDisp = traceback.format_exc(sys.exc_info()[2])
	finally:
		omsgbox(oDisp,1)

GReEp-)[General]











Audio

[ Sound ]

GASnd-)[General]Windows Sytem音を鳴らす( only Windows )

#!
#!
#coding: utf-8
# python Marco
import winsound
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title'):
#	"""shows message."""
		desktop = XSCRIPTCONTEXT.getDesktop()
		frame = desktop.getCurrentFrame()
		window = frame.getContainerWindow()
		toolkit = window.getToolkit()
		msgbox = toolkit.createMessageBox(window, MESSAGEBOX, oBtnType, oTitle, oMessage)
		return msgbox.execute()
def oTest():
	try:
		winsound.Beep(500, 500)
		winsound.PlaySound('SystemAsterisk', winsound.SND_ALIAS)
		winsound.PlaySound('SystemExclamation', winsound.SND_ALIAS)
		winsound.PlaySound('SystemExit', winsound.SND_ALIAS)
		winsound.PlaySound('SystemHand', winsound.SND_ALIAS)
		#winsound.PlaySound('SystemQuestion', winsound.SND_ALIAS)		#←音が出なくなるのでコメント化
		#
		oDisp = 'Success'
	except Exception as er:
		oDisp = ''
		oDisp = str(traceback.format_exc()) + '\n' + str(er)
	finally:
		omsgbox(oDisp,1,'LO6.2.4.2(x64)')
#
# 1) 全ての Win32 Systemは少なくとも以下の名前をSupportします; ほとんどのSystemでは他に多数あります。
#
# PlaySound() name    / 対応するControl Pannelでの音声名
# 'SystemAsterisk'    / Asterisk : 作業が完了した時などによく鳴る音
# 'SystemExclamation' / Exclamation : いわゆる警告音。確認事項があったりする時のWindowの出現と同時によく鳴る音
# 'SystemExit'        / Exit Windows : Windows終了時に鳴る音
# 'SystemHand'        / Critical Stop : Error音
# 'SystemQuestion'    / Question : 

GASnd-)[General]











[ Audio File ]

GASnd-)[General]wave FileのOpen / Close

#!
#coding: utf-8
# python Marco
import wave
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title',MsgType=MESSAGEBOX):
#	"""shows message."""
		desktop = XSCRIPTCONTEXT.getDesktop()
		frame = desktop.getCurrentFrame()
		window = frame.getContainerWindow()
		toolkit = window.getToolkit()
		msgbox = toolkit.createMessageBox(window, MsgType, oBtnType, oTitle, oMessage)
		return msgbox.execute()
def oTest():
	try:
		oWaveFile = 'C:\Windows\Media\chimes.wav'
		oWaveObj = wave.open(oWaveFile,'r')
		oWaveObj.close()
		#
		oDisp = 'Success'
	except wave.Error:
		oDisp = 'Audio Error'
	except:
		oDisp = traceback.format_exc(sys.exc_info()[2])
	finally:
		omsgbox(oDisp,1)

GASnd-)[General]Sound Fileの識別


#!
#coding: utf-8
# python Marco
import sndhdr
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title',MsgType=MESSAGEBOX):
#	"""shows message."""
		desktop = XSCRIPTCONTEXT.getDesktop()
		frame = desktop.getCurrentFrame()
		window = frame.getContainerWindow()
		toolkit = window.getToolkit()
		msgbox = toolkit.createMessageBox(window, MsgType, oBtnType, oTitle, oMessage)
		return msgbox.execute()
def oTest():
	try:
		oWaveFile = 'C:\Windows\Media\chimes.wav'
		oSndType1 = sndhdr.what(oWaveFile)
		oSndType2 = sndhdr.whathdr(oWaveFile)
		#
		oDisp = u'[ Sound Fileの識別 ]\n'\
		+ 'sndhdr.what() : ' + str(oSndType1) + '\n'\
		+ 'sndhdr.whathdr() : ' + str(oSndType1)
	except wave.Error:
		oDisp = 'Audio Error'
	except:
		oDisp = traceback.format_exc(sys.exc_info()[2])
	finally:
		omsgbox(oDisp,1)
#
# Return値 : (type, sampling_rate, channels, frames, bits_per_sample) 
# type : Data形式  / 'aifc', 'aiff', 'au', 'hcom', 'sndr', 'sndt', 'voc', 'wav', '8svx', 'sb', 'ub', 'ul'の何れか。
# sampling_rate : 実際のSampling Grade値で、未知の場合や読み取ることが出来なかった場合は 0 になる。
# channels : Channel数で、識別できない場合や読み取ることが出来なかった場合は 0  になる。
# frames : Frame数で、識別できない場合は -1 になる。
# bits_per_sample : Sampling Sizeを示すBit数ですが、A-LAWなら 'A', u-LAWなら 'U' 

GASnd-)[General]











Japanese Coding

GJp-)[General]日本語文字を扱う際の注意事項
[ Code中の文字 ]
	Python Interpreterはource Codeがどんな文字Encoding方法を使って記述されているのかを認識します。
	従って、Code中に日本語が含まれる時はソースコードの一行目か二行目に次のように書きます。

		# coding: エンコーディング名	=>	# Coding: utf-8
				or
		# coding=エンコーディング名		=>	# Coding=utf8

	また、「coding: エンコーディング名」の前後には余計な文字列を書くこともできます。利用するEditorによって
	
		Emacs 	=>  # -*- coding: euc-jp -*-
		vim		=>  # vim: fileencoding=euc-jp

	のようにするといいらしいです。


[ Python文字 ]
	Pythonには
	
		1) 文字列			=>		'Hello, world!!'
		2) Unicode文字列 	=>		u'Hello, world!!'
	
	がある。
	日本語の様なmulti-byte文字列を扱う時はunicode型の方が楽である。
 	また、主なCodingを以下に示す。
 	
 		・utf-8( utf-8 )
 		・Shift JIS( shift_jis )
 		・EUC JP( euc-jp )
 	
 	
[ 文字列型 ]
#!
# coding: utf-8			# Code中に日本語がある場合は必須
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title',MsgType=MESSAGEBOX):
#	"""shows message."""
		desktop = XSCRIPTCONTEXT.getDesktop()
		frame = desktop.getCurrentFrame()
		window = frame.getContainerWindow()
		toolkit = window.getToolkit()
		msgbox = toolkit.createMessageBox(window, MsgType, oBtnType, oTitle, oMessage)
		return msgbox.execute()
#
def oTest():
	try:
		oStr = '日本語のテストでーす'
		#oDisp = unicode(oStr,'utf-8') ← Python3.3 では unicode関数は廃止
		oDisp = oStr
	except:
		oDisp = traceback.format_exc(sys.exc_info()[2])
	finally:
		omsgbox(oDisp,1)
		
に対して
[ unicode型文字列 ]

#!
# coding: utf-8			# Code中に日本語がある場合は必須
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title',MsgType=MESSAGEBOX):
#	"""shows message."""
		desktop = XSCRIPTCONTEXT.getDesktop()
		frame = desktop.getCurrentFrame()
		window = frame.getContainerWindow()
		toolkit = window.getToolkit()
		msgbox = toolkit.createMessageBox(window, MsgType, oBtnType, oTitle, oMessage)
		return msgbox.execute()
#
def oTest():
	try:
		oStr = u'日本語のテストでーす'
		oDisp = oStr		# unicode(oStr,'utf-8')はError
	except:
		oDisp = traceback.format_exc(sys.exc_info()[2])
	finally:
		omsgbox(oDisp,1)
		
となる。


[ 文字長さ ]
	Unicode 文字列は 1 文字を 1 文字としてきちんと認識しますが、普通の文字列は単なるバイト列として扱います。
	そのため文字列の長さを求めようとした場合、結果に違いがありますので注意が必要です。
	UTF-8の場合は日本語1文字が3バイトとなります。他の形式では日本語1文字が2バイト。
	

GJp-)[General]文字列型とunicode型の違い


#!
# coding: utf-8			# Code中に日本語がある場合は必須
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title',MsgType=MESSAGEBOX):
#	"""shows message."""
		desktop = XSCRIPTCONTEXT.getDesktop()
		frame = desktop.getCurrentFrame()
		window = frame.getContainerWindow()
		toolkit = window.getToolkit()
		msgbox = toolkit.createMessageBox(window, MsgType, oBtnType, oTitle, oMessage)
		return msgbox.execute()
#
def oTest():
	try:
		oStr = '日本語のテストでーす。( 文字列 )'
		oStr_1 = str(oStr[2])	# 3番目の文字を取出す
		oStr_2 = str(oStr[1:4])	# 2から4番目の文字を取出す
		oUniStr = u'日本語のテストでーす。( unicode )'
		oUniStr_1 = oUniStr[2]
		oUniStr_2 = oUniStr[1:4]
		oDisp = '1) ' + oStr_1 + '\n' + '2) ' + oStr_2
		omsgbox(oDisp,1)
		oDisp = '3) ' + oUniStr_1 + '\n' + '4) ' + oUniStr_2
	except:
		oDisp = traceback.format_exc(sys.exc_info()[2])
	finally:
		omsgbox(oDisp,1)
#
# 1つの変数内のcodecは同じで無ければならない。oDispPreとoDispを一緒には出来ない。

GJp-)[General]Default Cording 1


#!
# coding: utf-8			# Code中に日本語がある場合は必須
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title',MsgType=MESSAGEBOX):
#	"""shows message."""
		desktop = XSCRIPTCONTEXT.getDesktop()
		frame = desktop.getCurrentFrame()
		window = frame.getContainerWindow()
		toolkit = window.getToolkit()
		msgbox = toolkit.createMessageBox(window, MsgType, oBtnType, oTitle, oMessage)
		return msgbox.execute()
#
def oTest():
	try:
		oStr = '日本語のテストでーす。( 文字列型 )'
		oUniStr = u'日本語のテストでーす。( unicode )'
		oDisp = u'[ 日本語codecの比較 ]' + '\n\n'\
		+ '1) ' + oStr + '\n'\						# ← Python3.xでは文字列はByte型になったので oStr だけでOK。unicode関数は廃止されたので unicode(oStr,'utf-8') はError 
		oDisp = oDisp + '2) ' + oUniStr
	except:
		oDisp = traceback.format_exc(sys.exc_info()[2])
	finally:
		omsgbox(oDisp,1)

GJp-)[General]Default Cording 2


#!
# coding: utf-8			# Code中に日本語がある場合は必須
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title',MsgType=MESSAGEBOX):
#	"""shows message."""
		desktop = XSCRIPTCONTEXT.getDesktop()
		frame = desktop.getCurrentFrame()
		window = frame.getContainerWindow()
		toolkit = window.getToolkit()
		msgbox = toolkit.createMessageBox(window, MsgType, oBtnType, oTitle, oMessage)
		return msgbox.execute()
#
def oTest():
	try:
		oStr = '日本語のテストでーす。( 文字列型 )'
		oUniStr = u'日本語のテストでーす。( unicode )'
		oDisp = u'[ 日本語codecの比較(2) ]' + '\n\n'\
		+ '1) ' + oStr + '\n'\
		+ '2) ' + oUniStr
	except:
		oDisp = traceback.format_exc(sys.exc_info()[2])
	finally:
		omsgbox(oDisp,1)

GJp-)[General]Editorと異なるCodingに変換した時の例(1)[ Error になる ]


#!
# coding: utf-8			# Code中に日本語がある場合は必須
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title',MsgType=MESSAGEBOX):
#	"""shows message."""
		desktop = XSCRIPTCONTEXT.getDesktop()
		frame = desktop.getCurrentFrame()
		window = frame.getContainerWindow()
		toolkit = window.getToolkit()
		msgbox = toolkit.createMessageBox(window, MsgType, oBtnType, oTitle, oMessage)
		return msgbox.execute()
#
def oTest():
	try:
		oStr = '日本語のテストでーす。( shift_jis )'
		oShft_Jis = oStr.decode('shift_jis','ignore')
		oDisp = '1) ' + oShft_Jis
	except:
		oDisp = traceback.format_exc(sys.exc_info()[2])
	finally:
		omsgbox(oDisp,1)
#
# .decode('shift_jis','ignore')の第2引数「'ignore'」は変換Errorが生じた時の指示を示しており、
# 'ignore'は変換エラーが起こった文字列をそのまま残す事を意味する。

GJp-)[General]Editorと異なるCodingに変換した時の例(2)


#!
# coding: utf-8			# Code中に日本語がある場合は必須
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title',MsgType=MESSAGEBOX):
#	"""shows message."""
		desktop = XSCRIPTCONTEXT.getDesktop()
		frame = desktop.getCurrentFrame()
		window = frame.getContainerWindow()
		toolkit = window.getToolkit()
		msgbox = toolkit.createMessageBox(window, MsgType, oBtnType, oTitle, oMessage)
		return msgbox.execute()
#
def oTest():
	try:
		oStr = '日本語のテストでーす。( euc-jp )'
		oEuc_Jp = oStr.decode('euc-jp','ignore')
		oDisp = '1) ' + oEuc_Jp
	except:
		oDisp = traceback.format_exc(sys.exc_info()[2])
	finally:
		omsgbox(oDisp,1)

GJp-)[General]日本語文字の長さ( UTF-8 )1


#!
# coding: utf-8			# Code中に日本語がある場合は必須
import uno
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title',MsgType=MESSAGEBOX):
#	"""shows message."""
		desktop = XSCRIPTCONTEXT.getDesktop()
		frame = desktop.getCurrentFrame()
		window = frame.getContainerWindow()
		toolkit = window.getToolkit()
		msgbox = toolkit.createMessageBox(window, MsgType, oBtnType, oTitle, oMessage)
		return msgbox.execute()

def oTest():
    try:
		oJpWord = '日本語のテストで~す。'
		oDecode = oJpWord.decode('utf-8')
		oDisp = 'The character length of ' + oDecode + '\n\
		is ' + str(len(oJpWord))
		omsgbox(oDisp)
    except:
        pass

GJp-)[General]日本語文字の長さ( UTF-8 )2[ decode関数Error ]


#!
# coding: utf-8			# Code中に日本語がある場合は必須
import uno
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title',MsgType=MESSAGEBOX):
#	"""shows message."""
		desktop = XSCRIPTCONTEXT.getDesktop()
		frame = desktop.getCurrentFrame()
		window = frame.getContainerWindow()
		toolkit = window.getToolkit()
		msgbox = toolkit.createMessageBox(window, MsgType, oBtnType, oTitle, oMessage)
		return msgbox.execute()

def oTest():
    try:
		oJpWord = '日本語のテストで~す。'
		oDecode = oJpWord.decode('utf-8')
		oDisp = u'「 ' + oDecode + u' 」の文字長さは' + '\n\
		' + str(len(oJpWord)) + u' ( UTF-8の場合)'
		omsgbox(oDisp)
    except:
        pass

GJp-)[General]日本語文字の長さ( EUC-JP )[ decode関数Error ]


#!
# coding: euc-jp			# Code中に日本語がある時は必須
import uno
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title',MsgType=MESSAGEBOX):
#	"""shows message."""
		desktop = XSCRIPTCONTEXT.getDesktop()
		frame = desktop.getCurrentFrame()
		window = frame.getContainerWindow()
		toolkit = window.getToolkit()
		msgbox = toolkit.createMessageBox(window, MsgType, oBtnType, oTitle, oMessage)
		return msgbox.execute()
def oTest():
    try:
		oJpWord = '日本語のテストで~す。'
		oDecode = oJpWord.decode('euc-jp')
		oDisp = unicode('「 ','euc-jp') + oDecode + unicode(' 」の文字長さは','euc-jp') + '\n\
		' + str(len(oJpWord)) + unicode(' ( EUC-JPの場合 )','euc-jp')
		omsgbox(oDisp)
    except:
        pass

GJp-)[General]日本語文字の長さ( Shift-JIS )[ decode関数Error ]


#!
# coding: shift_jis			# Code中に日本語がある時は必須
import uno
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title',MsgType=MESSAGEBOX):
#	"""shows message."""
		desktop = XSCRIPTCONTEXT.getDesktop()
		frame = desktop.getCurrentFrame()
		window = frame.getContainerWindow()
		toolkit = window.getToolkit()
		msgbox = toolkit.createMessageBox(window, MsgType, oBtnType, oTitle, oMessage)
		return msgbox.execute()

def oTest():
    try:
		oJpWord = '日本語のテストで~す。'
		oDecode = oJpWord.decode('shift_jis')
		oDisp = unicode('「 ','shift_jis') + oDecode + unicode(' 」の文字長さは','shift_jis') + '\n\
		' + str(len(oJpWord)) + unicode(' ( Shift-JISの場合 )','shift_jis')
		omsgbox(oDisp)
    except:
        pass

GJp-)[General]PythonのDefault Encoding


#!
#coding: utf-8
# python Marco
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title',MsgType=MESSAGEBOX):
#	"""shows message."""
		desktop = XSCRIPTCONTEXT.getDesktop()
		frame = desktop.getCurrentFrame()
		window = frame.getContainerWindow()
		toolkit = window.getToolkit()
		msgbox = toolkit.createMessageBox(window, MsgType, oBtnType, oTitle, oMessage)
		return msgbox.execute()
def otest():
	try:
		oPyEncode = sys.getdefaultencoding()
		oDisp = u'[ PythonのDefault Encode ]\n => ' + str(oPyEncode)
	except:
		oDisp = traceback.format_exc(sys.exc_info()[2])
	finally:
		omsgbox(oDisp,1)

GJp-)[General]UnicodeのFile NameのEncoding


#!
#coding: utf-8
# python Marco
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title',MsgType=MESSAGEBOX):
#	"""shows message."""
		desktop = XSCRIPTCONTEXT.getDesktop()
		frame = desktop.getCurrentFrame()
		window = frame.getContainerWindow()
		toolkit = window.getToolkit()
		msgbox = toolkit.createMessageBox(window, MsgType, oBtnType, oTitle, oMessage)
		return msgbox.execute()
def otest():
	try:
		oPyEncode = sys.getfilesystemencoding()
		oDisp = u'[ File NameのEncoding ]\n => ' + str(oPyEncode)
	except:
		oDisp = traceback.format_exc(sys.exc_info()[2])
	finally:
		omsgbox(oDisp,1)
#
# Windows9x系		: mbcs
# WindowsNT系		: unicodeをFile名に使えるので変換(Encoding)の必要は無い。但し上記Codeでは「mbcs」と表わされる。
# Unix				: nl_langinfo(CODESET)のReturn値 / Retun値取得に失敗した時はNone
# Mac OS X系		: utf-8 

GJp-)[General]unicode型の内部表現


#!
#coding: utf-8
# python Marco
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title',MsgType=MESSAGEBOX):
#	"""shows message."""
		desktop = XSCRIPTCONTEXT.getDesktop()
		frame = desktop.getCurrentFrame()
		window = frame.getContainerWindow()
		toolkit = window.getToolkit()
		msgbox = toolkit.createMessageBox(window, MsgType, oBtnType, oTitle, oMessage)
		return msgbox.execute()
def otest():
	try:
		oSys = sys.maxunicode
		if oSys == 65535:
			oEncode = 'UTF-16'
		elif oSys == 1114111:
			oEncode = 'UTF-32'
		else:
			oEncode = 'None'
		oDisp = u'[ unicodeの内部表現 ]\n => ' + str(oEncode)
	except:
		oDisp = traceback.format_exc(sys.exc_info()[2])
	finally:
		omsgbox(oDisp,1)
#
# unicode型の内部表現にはUTF-16とUTF-32がある。

GJp-)[General]codecs module(1)


#!
#coding: utf-8
# python Marco
import codecs
import sys
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title',MsgType=MESSAGEBOX):
#	"""shows message."""
		desktop = XSCRIPTCONTEXT.getDesktop()
		frame = desktop.getCurrentFrame()
		window = frame.getContainerWindow()
		toolkit = window.getToolkit()
		msgbox = toolkit.createMessageBox(window, MsgType, oBtnType, oTitle, oMessage)
		return msgbox.execute()
def oTest():
	try:
		# Open File
		oFile = 'c:\\temp\\oTextMacro.txt'
		# 読込み文字Code指定( NotePad作成 File )
		oFileObj = codecs.open(oFile,'r','shift_jis')
		oTxtSrc = oFileObj.readline()
		oFileObj.close()
		# 
		oDisp = oTxtSrc.encode('shift_jis')
	except:
		oDisp = traceback.format_exc(sys.exc_info()[2])
	finally:
		omsgbox(oDisp,1)

GJp-)[General]codecs module(2)


#!
#coding: utf-8
# python Marco
import codecs
import sys
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title',MsgType=MESSAGEBOX):
#	"""shows message."""
		desktop = XSCRIPTCONTEXT.getDesktop()
		frame = desktop.getCurrentFrame()
		window = frame.getContainerWindow()
		toolkit = window.getToolkit()
		msgbox = toolkit.createMessageBox(window, MsgType, oBtnType, oTitle, oMessage)
		return msgbox.execute()
def oTest():
	try:
		# Open File
		oFile = 'c:\\temp\\oTextMacro.txt'
		# 読込み文字Code指定( NotePad作成 File )
		oFileObj = codecs.open(oFile,'r','shift_jis')
		oTxtSrc = oFileObj.readlines()
		oFileObj.close()
		# 改行文字はEncode不可の為、各行で行う。
		oDisp = ''
		for oLine in oTxtSrc:
			oDisp = oDisp + oLine.encode('shift_jis')
	except:
		oDisp = traceback.format_exc(sys.exc_info()[2])
	finally:
		omsgbox(oDisp,1)

GJp-)[General]











Internationalization / Localization

GIntLcl-)[General]Localization設定取得


#!
#coding: utf-8
# python Marco
import locale
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title',MsgType=MESSAGEBOX):
#	"""shows message."""
		desktop = XSCRIPTCONTEXT.getDesktop()
		frame = desktop.getCurrentFrame()
		window = frame.getContainerWindow()
		toolkit = window.getToolkit()
		msgbox = toolkit.createMessageBox(window, MsgType, oBtnType, oTitle, oMessage)
		return msgbox.execute()
def oTest():
	try:
		# User環境に基づいたDefault設定
		locale.setlocale(locale.LC_ALL, '')
		oDft_Locale = locale.getdefaultlocale()
		oCur_Locale = locale.getlocale()
		#
		oDisp = u'[ Localization / 地域化 ]\n'\
		+ str(oDft_Locale) + '\n'\
		+ str(oCur_Locale)
	except locale.Error:
		oDisp = u'setlocale() が失敗しました。'
	except:
		oDisp = traceback.format_exc(sys.exc_info()[2])
	finally:
		omsgbox(oDisp,1)

GIntLcl-)[General]











認証

GAuthn-)[General]Basic認証 / BASE64


#!
#coding: utf-8
# python Marco
import base64
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
#
def omsgbox(oMessage='',oBtnType=1,oTitle='Title'):
#	"""shows message."""
		desktop = XSCRIPTCONTEXT.getDesktop()
		frame = desktop.getCurrentFrame()
		window = frame.getContainerWindow()
		toolkit = window.getToolkit()
		msgbox = toolkit.createMessageBox(window, MESSAGEBOX, oBtnType, oTitle, oMessage)
		return msgbox.execute()
def Test():
	try:
		oTxt = 'A2cD5fG'
		oEncode = base64.b64encode(oTxt.encode('utf-8'))
		oDecode = base64.decodestring(oEncode)
		oDisp = u'[ BASIC認証 / BASE64 ]\n'\
		+ u'初期文字 : ' + str(oTxt) + '\n'\
		+ u'Encode( 暗号化後の文字 ) : ' + str(oEncode) + '\n'\
		+ u'Decode( 元に戻した文字 ) : ' + str(oDecode)
	except Exception as er:
		oDisp = ''
		oDisp = str(traceback.format_exc()) + '\n' + str(er)
	finally:
		omsgbox(oDisp,1,'LO6.2.4(x64)')

GAuthn-)[General]MD5 / SHA


#!
#coding: utf-8
# python Marco
import hashlib
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
#
def omsgbox(oMessage='',oBtnType=1,oTitle='Title'):
#	"""shows message."""
		desktop = XSCRIPTCONTEXT.getDesktop()
		frame = desktop.getCurrentFrame()
		window = frame.getContainerWindow()
		toolkit = window.getToolkit()
		msgbox = toolkit.createMessageBox(window, MESSAGEBOX, oBtnType, oTitle, oMessage)
		return msgbox.execute()
def oTest():
	try:
		oPassword = 'password'
		oMd5 = hashlib.md5(oPassword.encode()).hexdigest()
		oSha = hashlib.sha1(oPassword.encode()).hexdigest()
		oDisp = u'[ Hash関数( MD5 / SHA ) ]\n'\
		+ u'初期文字 : ' + str(oPassword) + '\n'\
		+ u'MD5 Object( 16進数文字列表記 )\n = ' + str(oMd5) + '\n'\
		+ u'SHA Object( 16進数文字列表記 )\n = ' + str(oSha)
	except Exception as er:
		oDisp = ''
		oDisp = str(traceback.format_exc()) + '\n' + str(er)
	finally:
		omsgbox(oDisp,1,'LO6.2.4(x64)')

GAuthn-)[General]UUID生成


#!
#coding: utf-8
# python Marco
import uuid
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
#
def omsgbox(oMessage='',oBtnType=1,oTitle='Title'):
#	"""shows message."""
		desktop = XSCRIPTCONTEXT.getDesktop()
		frame = desktop.getCurrentFrame()
		window = frame.getContainerWindow()
		toolkit = window.getToolkit()
		msgbox = toolkit.createMessageBox(window, MESSAGEBOX, oBtnType, oTitle, oMessage)
		return msgbox.execute()
def Test():
	try:
		oUuId = uuid.uuid4()
		oDisp = u'[ UUID生成 ]\n' + str(oUuId)
	except Exception as er:
		oDisp = ''
		oDisp = str(traceback.format_exc()) + '\n' + str(er)
	finally:
		omsgbox(oDisp,1,'LO6.2.4(x64)')

GAuthn-)[General]











Exception

GExpt-)[General]Error内容取得


#!
#coding: utf-8
# python Marco
import datetime
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title',MsgType=MESSAGEBOX):
#	"""shows message."""
		desktop = XSCRIPTCONTEXT.getDesktop()
		frame = desktop.getCurrentFrame()
		window = frame.getContainerWindow()
		toolkit = window.getToolkit()
		msgbox = toolkit.createMessageBox(window, MsgType, oBtnType, oTitle, oMessage)
		return msgbox.execute()
def otest():
	try:
		oToday = datetime.datetime.today()
		aDate = datetime.datetime(2001,8,11)
		# うるう年も考慮される
		oDayDiff = aToday - aDate
		oDisp = str(oDayDiff)
	# Python2.7
	# except:
	#	oDisp = traceback.format_exc(sys.exc_info()[2])
	# Python3.3
	except Exception as er:
		oDisp = ''
		oDisp = str(traceback.format_exc()) + '\n' + str(er)
	finally:
		omsgbox(oDisp)

GExpt-)[General]Script途中での処理終了


#!
#coding: utf-8
# python Marco
import datetime
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title',MsgType=MESSAGEBOX):
#	"""shows message."""
		desktop = XSCRIPTCONTEXT.getDesktop()
		frame = desktop.getCurrentFrame()
		window = frame.getContainerWindow()
		toolkit = window.getToolkit()
		msgbox = toolkit.createMessageBox(window, MsgType, oBtnType, oTitle, oMessage)
		return msgbox.execute()
def otest():
	try:
		oDisp = u'処理を終了しますか?'
		oAns = omsgbox(oDisp,3,'Script Exit','querybox')
		if oAns == 2:
			sys.exit([0])
		oDisp = u'処理継続が選択されました。'
	except SystemExit:
		oDisp = u'処理を終了します。'
	except:
		oDisp = traceback.format_exc(sys.exc_info()[2])
	finally:
		omsgbox(oDisp,1)

GExpt-)[General]警告制御Option


#!
#coding: utf-8
# python Marco
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title',MsgType=MESSAGEBOX):
#	"""shows message."""
		desktop = XSCRIPTCONTEXT.getDesktop()
		frame = desktop.getCurrentFrame()
		window = frame.getContainerWindow()
		toolkit = window.getToolkit()
		msgbox = toolkit.createMessageBox(window, MsgType, oBtnType, oTitle, oMessage)
		return msgbox.execute()
def otest():
	try:
		oSys = sys.warnoptions
		oDisp = u'[ 警告制御Option ]\n => ' + str(oSys)
	except:
		oDisp = traceback.format_exc(sys.exc_info()[2])
	finally:
		omsgbox(oDisp,1)

GExpt-)[General]強制的に例外を送出する


#!
#coding: utf-8
# python Marco
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title',MsgType=MESSAGEBOX):
#	"""shows message."""
		desktop = XSCRIPTCONTEXT.getDesktop()
		frame = desktop.getCurrentFrame()
		window = frame.getContainerWindow()
		toolkit = window.getToolkit()
		msgbox = toolkit.createMessageBox(window, MsgType, oBtnType, oTitle, oMessage)
		return msgbox.execute()
def otest():
	try:
		raise NameError
	except NameError:
		oDisp = 'NameError !!'
	except:
		oDisp = traceback.format_exc(sys.exc_info()[2])
	finally:
		omsgbox(oDisp,1)

GExpt-)[General]


#!
#coding: utf-8
# python Marco
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title',MsgType=MESSAGEBOX):
#	"""shows message."""
		desktop = XSCRIPTCONTEXT.getDesktop()
		frame = desktop.getCurrentFrame()
		window = frame.getContainerWindow()
		toolkit = window.getToolkit()
		msgbox = toolkit.createMessageBox(window, MsgType, oBtnType, oTitle, oMessage)
		return msgbox.execute()
def otest():
	try:
		raise NameError
	except (RuntimeError, TypeError, NameError):
		oDisp = 'RuntimeError or TypeError or NameError !!'
	except:
		oDisp = traceback.format_exc(sys.exc_info()[2])
	finally:
		omsgbox(oDisp,1)

GExpt-)[General]例外の詳細説明


#!
#coding: utf-8
# python Marco
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title',MsgType=MESSAGEBOX):
#	"""shows message."""
		desktop = XSCRIPTCONTEXT.getDesktop()
		frame = desktop.getCurrentFrame()
		window = frame.getContainerWindow()
		toolkit = window.getToolkit()
		msgbox = toolkit.createMessageBox(window, MsgType, oBtnType, oTitle, oMessage)
		return msgbox.execute()
def otest():
	try:
		def oFail():
			x = 1/0
			return x
		oChk = oFail()
	except ZeroDivisionError, detail:
		oDisp = 'Exception Detail \n => ' + str(detail)
	except:
		oDisp = traceback.format_exc(sys.exc_info()[2])
	finally:
		omsgbox(oDisp,1)

GExpt-)[General]User定義のException


#!
#coding: utf-8
# python Marco
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title',MsgType=MESSAGEBOX):
#	"""shows message."""
		desktop = XSCRIPTCONTEXT.getDesktop()
		frame = desktop.getCurrentFrame()
		window = frame.getContainerWindow()
		toolkit = window.getToolkit()
		msgbox = toolkit.createMessageBox(window, MsgType, oBtnType, oTitle, oMessage)
		return msgbox.execute()
class MyError(Exception):			# class名の先頭文字は大文字
	def __init__(self, oVal):
		self.value = oVal
		def __str__(self):
			return repr(self.value)
def otest():
	try:
		raise MyError(2*5)
	except MyError as e:		# <= MyError という名の例外をcatchする
		oDisp = 'User Defined Exception \n Value = ' + str(e.value)
	except:
		oDisp = traceback.format_exc(sys.exc_info()[2])
	finally:
		omsgbox(oDisp,1)

GExpt-)[General]Error NoとError Message


#!
#coding: utf-8
# python Marco
import errno
import os
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title',MsgType=MESSAGEBOX):
#	"""shows message."""
		desktop = XSCRIPTCONTEXT.getDesktop()
		frame = desktop.getCurrentFrame()
		window = frame.getContainerWindow()
		toolkit = window.getToolkit()
		msgbox = toolkit.createMessageBox(window, MsgType, oBtnType, oTitle, oMessage)
		return msgbox.execute()
def oTest():
	try:
		oErrKey = errno.errorcode.keys()
		oDisp = u'[ Error Code NoとError ]\n'
		for er in oErrKey:
			oErrCode = os.strerror(er)
			oDisp = oDisp + str(er) + ' : ' + str(oErrCode) + '\n'
	except:
		oDisp = traceback.format_exc(sys.exc_info()[2])
	finally:
		omsgbox(oDisp,1)
#
# [ 取得Symbol ]
# EPERM : 許可されていない操作です (Operation not permitted)
# ENOENT : ファイルまたはディレクトリがありません (No such file or directory)
# ESRCH : 指定したプロセスが存在しません (No such process)
# EINTR : 割り込みシステムコールです (Interrupted system call)
# EIO : I/O エラーです (I/O error)
# ENXIO : そのようなデバイスまたはアドレスはありません (No such device or address)
# E2BIG : 引数リストが長すぎます (Arg list too long)
# ENOEXEC : 実行形式にエラーがあります (Exec format error)
# EBADF : ファイル番号が間違っています (Bad file number)
# ECHILD : 子プロセスがありません (No child processes)
# EAGAIN : 再試行してください (Try again)
# ENOMEM : 空きメモリがありません (Out of memory)
# EACCES : 許可がありません (Permission denied)
# EFAULT : 不正なアドレスです (Bad address)
# ENOTBLK : ブロックデバイスが必要です (Block device required)
# EBUSY : そのデバイスまたは資源は使用中です (Device or resource busy)
# EEXIST : ファイルがすでに存在します	(File exists)
# EXDEV : デバイス間のリンクです (Cross-device link)
# ENODEV : そのようなデバイスはありません (No such device)
# ENOTDIR : ディレクトリではありません (Not a directory)
# EISDIR : ディレクトリです (Is a directory)
# EINVAL : 無効な引数です (Invalid argument)
# ENFILE : ファイルテーブルがオーバフローしています (File table overflow)
# EMFILE : 開かれたファイルが多すぎます (Too many open files)
# ENOTTY : タイプライタではありません (Not a typewriter)
# ETXTBSY : テキストファイルが使用中です (Text file busy)
# EFBIG : ファイルが大きすぎます (File too large)
# ENOSPC : デバイス上に空きがありません (No space left on device)
# ESPIPE : 不正なシークです (Illegal seek)
# EROFS : 読み出し専用ファイルシステムです (Read-only file system)
# EMLINK : リンクが多すぎます (Too many links)
# EPIPE : パイプが壊れました (Broken pipe)
# EDOM : 数学引数が関数の定義域を越えています (Math argument out of domain of func)
# ERANGE : 表現できない数学演算結果になりました (Math result not representable)
# EDEADLK : リソースのデッドロックが起きます (Resource deadlock would occur)
# ENAMETOOLONG : ファイル名が長すぎます (File name too long)
# ENOLCK : レコードロッキングが利用できません (No record locks available)
# ENOSYS : 実装されていない機能です (Function not implemented)
# ENOTEMPTY : ディレクトリが空ではありません (Directory not empty)
# ELOOP : これ以上シンボリックリンクを追跡できません (Too many symbolic links encountered)
# EWOULDBLOCK : 操作がブロックします (Operation would block)
# ENOMSG : 指定された型のメッセージはありません (No message of desired type)
# EIDRM : 識別子が除去されました (Identifier removed)
# ECHRNG : チャネル番号が範囲を超えました (Channel number out of range)
# EL2NSYNC : レベル 2 で同期がとれていません (Level 2 not synchronized)
# EL3HLT : レベル 3 で終了しました (Level 3 halted)
# EL3RST : レベル 3 でリセットしました (Level 3 reset)
# ELNRNG : リンク番号が範囲を超えています (Link number out of range)
# EUNATCH : プロトコルドライバが接続されていません (Protocol driver not attached)
# ENOCSI : CSI 構造体がありません (No CSI structure available)
# EL2HLT : レベル 2 で終了しました (Level 2 halted)
# EBADE : 無効な変換です (Invalid exchange)
# EBADR : 無効な要求記述子です (Invalid request descriptor)
# EXFULL : 変換テーブルが一杯です (Exchange full)
# ENOANO : 陰極がありません (No anode)
# EBADRQC : 無効なリクエストコードです (Invalid request code)
# EBADSLT : 無効なスロットです (Invalid slot)
# EDEADLOCK : ファイルロックにおけるデッドロックエラーです (File locking deadlock error)
# EBFONT : フォントファイル形式が間違っています (Bad font file format)
# ENOSTR : ストリーム型でないデバイスです (Device not a stream)
# ENODATA : 利用可能なデータがありません (No data available)
# ETIME : 時間切れです (Timer expired)
# ENOSR : streams リソースを使い切りました (Out of streams resources)
# ENONET : 計算機はネットワーク上にありません (Machine is not on the network)
# ENOPKG : パッケージがインストールされていません (Package not installed)
# EREMOTE : 対象物は遠隔にあります (Object is remote)
# ENOLINK : リンクが切られました (Link has been severed)
# EADV : Advertise エラーです (Advertise error)
# ESRMNT : Srmount エラーです (Srmount error)
# ECOMM : 送信時の通信エラーです (Communication error on send)
# EPROTO : プロトコルエラーです (Protocol error)
# EMULTIHOP : 多重ホップを試みました (Multihop attempted)
# EDOTDOT : RFS 特有のエラーです (RFS specific error)
# EBADMSG : データメッセージではありません (Not a data message)
# EOVERFLOW : 定義されたデータ型にとって大きすぎる値です (Value too large for defined data type)
# ENOTUNIQ : 名前がネットワーク上で一意でありません (Name not unique on network)
# EBADFD : ファイル記述子の状態が不正です (File descriptor in bad state)
# EREMCHG : 遠隔のアドレスが変更されました (Remote address changed)
# ELIBACC : 必要な共有ライブラリにアクセスできません (Can not access a needed shared library)
# ELIBBAD : 壊れた共有ライブラリにアクセスしています (Accessing a corrupted shared library)
# ELIBSCN : a.out の .lib セクションが壊れています (.lib section in a.out corrupted)
# ELIBMAX : リンクを試みる共有ライブラリが多すぎます (Attempting to link in too many shared libraries)
# ELIBEXEC : 共有ライブラリを直接実行することができません (Cannot exec a shared library directly)
# EILSEQ : 不正なバイト列です (Illegal byte sequence)
# ERESTART : 割り込みシステムコールを復帰しなければなりません (Interrupted system call should be restarted)
# ESTRPIPE : ストリームパイプのエラーです (Streams pipe error)
# EUSERS : ユーザが多すぎます (Too many users)
# ENOTSOCK : 非ソケットに対するソケット操作です (Socket operation on non-socket)
# EDESTADDRREQ : 目的アドレスが必要です (Destination address required)
# EMSGSIZE : メッセージが長すぎます (Message too long)
# EPROTOTYPE : ソケットに対して不正なプロトコル型です (Protocol wrong type for socket)
# ENOPROTOOPT : 利用できないプロトコルです (Protocol not available)
# EPROTONOSUPPORT : サポートされていないプロトコルです (Protocol not supported)
# ESOCKTNOSUPPORT : サポートされていないソケット型です (Socket type not supported)
# EOPNOTSUPP : 通信端点に対してサポートされていない操作です (Operation not supported on transport endpoint)
# EPFNOSUPPORT : サポートされていないプロトコルファミリです (Protocol family not supported)
# EAFNOSUPPORT : プロトコルでサポートされていないアドレスファミリです (Address family not supported by protocol)
# EADDRINUSE : アドレスは使用中です (Address already in use)
# EADDRNOTAVAIL : 要求されたアドレスを割り当てできません (Cannot assign requested address)
# ENETDOWN : ネットワークがダウンしています (Network is down)
# ENETUNREACH : ネットワークに到達できません (Network is unreachable)
# ENETRESET : リセットによってネットワーク接続が切られました (Network dropped connection because of reset)
# ECONNABORTED : ソフトウェアによって接続が終了されました (Software caused connection abort)
# ECONNRESET : 接続がピアによってリセットされました (Connection reset by peer)
# ENOBUFS : バッファに空きがありません (No buffer space available)
# EISCONN : 通信端点がすでに接続されています (Transport endpoint is already connected)
# ENOTCONN : 通信端点が接続されていません (Transport endpoint is not connected)
# ESHUTDOWN : 通信端点のシャットダウン後は送信できません (Cannot send after transport endpoint shutdown)
# ETOOMANYREFS : 参照が多すぎます: 接続できません (Too many references: cannot splice)
# ETIMEDOUT : 接続がタイムアウトしました (Connection timed out)
# ECONNREFUSED : 接続を拒否されました (Connection refused)
# EHOSTDOWN : ホストはシステムダウンしています (Host is down)
# EHOSTUNREACH : ホストへの経路がありません (No route to host)
# EALREADY : すでに処理中です (Operation already in progress)
# EINPROGRESS : 現在処理中です (Operation now in progress)
# ESTALE : 無効な NFS ファイルハンドルです (Stale NFS file handle)
# EUCLEAN : (Structure needs cleaning)
# ENOTNAM : XENIX 名前付きファイルではありません (Not a XENIX named type file)
# ENAVAIL : XENIX セマフォは利用できません (No XENIX semaphores available)
# EISNAM : 名前付きファイルです (Is a named type file)
# EREMOTEIO : 遠隔側の I/O エラーです (Remote I/O error)
# EDQUOT : ディスククオータを超えました (Quota exceeded)

GExpt-)[General]Log Fileに出力


#!
#coding: utf-8
# python Marco
import logging
import errno
import datetime
import os
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title',MsgType=MESSAGEBOX):
#	"""shows message."""
		desktop = XSCRIPTCONTEXT.getDesktop()
		frame = desktop.getCurrentFrame()
		window = frame.getContainerWindow()
		toolkit = window.getToolkit()
		msgbox = toolkit.createMessageBox(window, MsgType, oBtnType, oTitle, oMessage)
		return msgbox.execute()
def oTest():
	try:
		# Log Fileと出力Levelの設定
		oLogFile = 'c:\\temp\\Log\\PythonLog.txt'
		logging.basicConfig(level=logging.DEBUG,filename=oLogFile, filemode='w')	# filemode='w'は省略可( 注1 )
		# Except
		oCheck = 10/0
		oDisp = 'Suucess'
	except:
		oErr = str(datetime.datetime.today())
		oDebug = str(traceback.format_exc(sys.exc_info()[2]))
		logging.error(oErr)
		logging.debug(oDebug)
		oDisp = u'例外Errorが発生しました。\n 詳細はLog Fileを参照。'
	finally:
		omsgbox(oDisp,1)
#
# [ 注意 ]
# 1) Macro実行後のLog Fileの編集は不可。編集する為にはPython( つまりLibreOffice )を終了させる必要がある。
# 2) LibreOffice3.5ではfilemode='w'としてもDefaultと同じく追記になる。

GExpt-)[General]











Other

GOthr-)[General]登録したProfiler関数の取得


#!
#coding: utf-8
# python Marco
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title',MsgType=MESSAGEBOX):
#	"""shows message."""
		desktop = XSCRIPTCONTEXT.getDesktop()
		frame = desktop.getCurrentFrame()
		window = frame.getContainerWindow()
		toolkit = window.getToolkit()
		msgbox = toolkit.createMessageBox(window, MsgType, oBtnType, oTitle, oMessage)
		return msgbox.execute()
def otest():
	try:
		oPyProFiler = sys.getprofile
		oDisp = u'[ 登録したProfile関数 ]\n => ' + str(oPyProFiler)
	except:
		oDisp = traceback.format_exc(sys.exc_info()[2])
	finally:
		omsgbox(oDisp,1)
#
# Profilerとは、Program実行時の様々な状態を得ることにより、その実行効率を調べるためのProgramです。

GOthr-)[General]登録したtrace 関数の取得


#!
#coding: utf-8
# python Marco
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title',MsgType=MESSAGEBOX):
#	"""shows message."""
		desktop = XSCRIPTCONTEXT.getDesktop()
		frame = desktop.getCurrentFrame()
		window = frame.getContainerWindow()
		toolkit = window.getToolkit()
		msgbox = toolkit.createMessageBox(window, MsgType, oBtnType, oTitle, oMessage)
		return msgbox.execute()
def otest():
	try:
		oPyTrace = sys.gettrace()
		oDisp = u'[ 登録したtrace関数 ]\n => ' + str(oPyTrace)
	except:
		oDisp = traceback.format_exc(sys.exc_info()[2])
	finally:
		omsgbox(oDisp,1)

GOthr-)[General]importするmoduleがPackageに含まれる時の__path__属性取得


#!
#coding: utf-8
# python Marco
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title',MsgType=MESSAGEBOX):
#	"""shows message."""
		desktop = XSCRIPTCONTEXT.getDesktop()
		frame = desktop.getCurrentFrame()
		window = frame.getContainerWindow()
		toolkit = window.getToolkit()
		msgbox = toolkit.createMessageBox(window, MsgType, oBtnType, oTitle, oMessage)
		return msgbox.execute()
def otest():
	try:
		oSys = sys.meta_path
		oDisp = u'[ importするmoduleがPackageに含まれる時の__path__属性取得 ]\n => ' + str(oSys)
	except:
		oDisp = traceback.format_exc(sys.exc_info()[2])
	finally:
		omsgbox(oDisp,1)
#
# importするmoduleがPackageに含まれる場合、親Packageの__path__属性が第2引数として渡されます。
# 渡された属性のmethodsはmoduleが見つからなかった場合はNone
# 見つかった場合はloaderを返します。

GOthr-)[General]path_hooks


#!
#coding: utf-8
# python Marco
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title',MsgType=MESSAGEBOX):
#	"""shows message."""
		desktop = XSCRIPTCONTEXT.getDesktop()
		frame = desktop.getCurrentFrame()
		window = frame.getContainerWindow()
		toolkit = window.getToolkit()
		msgbox = toolkit.createMessageBox(window, MsgType, oBtnType, oTitle, oMessage)
		return msgbox.execute()
def otest():
	try:
		oSys = sys.path_hooks
		oDisp = u'[ path_hooks ]\n => ' + str(oSys)
	except:
		oDisp = traceback.format_exc(sys.exc_info()[2])
	finally:
		omsgbox(oDisp,1)

GOthr-)[General]path_importer_cache

#!
#coding: utf-8
# python Marco
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title',MsgType=MESSAGEBOX):
#	"""shows message."""
		desktop = XSCRIPTCONTEXT.getDesktop()
		frame = desktop.getCurrentFrame()
		window = frame.getContainerWindow()
		toolkit = window.getToolkit()
		msgbox = toolkit.createMessageBox(window, MsgType, oBtnType, oTitle, oMessage)
		return msgbox.execute()
def otest():
	try:
		oSys = sys.path_importer_cache
		oDisp = u'[ path_importer_cache ]\n => '
		for i in oSys:
			oDisp = oDisp + str(i) + ',' + str(oSys[i]) + '\n'
	except:
		oDisp = traceback.format_exc(sys.exc_info()[2])
	finally:
		omsgbox(oDisp,1)

GOthr-)[General]自動GCが有効かどうか


#!
#coding: utf-8
# python Marco
import gc
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title',MsgType=MESSAGEBOX):
#	"""shows message."""
		desktop = XSCRIPTCONTEXT.getDesktop()
		frame = desktop.getCurrentFrame()
		window = frame.getContainerWindow()
		toolkit = window.getToolkit()
		msgbox = toolkit.createMessageBox(window, MsgType, oBtnType, oTitle, oMessage)
		return msgbox.execute()
def otest():
	try:
		oGC = gc.isenabled()
		oDisp = u'[ 自動GCが有効かどうか ]\n => ' + str(oGC)
	except:
		oDisp = traceback.format_exc(sys.exc_info()[2])
	finally:
		omsgbox(oDisp,1)
#
# ガベージコレクション(garbage collection; GC)とは、Programが動的に確保したmemory領域のうち、
# 不要になった領域を自動的に解放する機能である。「ガベージコレクション」を直訳すれば「ゴミ収集」となる。
# また、自動GCが有効でなければ、「import GC」でErrorになる。

GOthr-)[General]Performance測定


#!
#coding: utf-8
# python Marco
import timeit
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title',MsgType=MESSAGEBOX):
#	"""shows message."""
		desktop = XSCRIPTCONTEXT.getDesktop()
		frame = desktop.getCurrentFrame()
		window = frame.getContainerWindow()
		toolkit = window.getToolkit()
		msgbox = toolkit.createMessageBox(window, MsgType, oBtnType, oTitle, oMessage)
		return msgbox.execute()
#
def oTest():
	try:
		oDisp = 'Timer'
		oTime = timeit.Timer('[n for n in range(1000000)]').timeit(1)
		oDisp = u'[ performance測定 ]\n' + str(oTime) + ' [ sec ]'
	except:
		oDisp = traceback.format_exc(sys.exc_info()[2])
	finally:
		omsgbox(oDisp)

GOthr-)[General]





Top of Page

inserted by FC2 system