Создать питона макроса в LibreOffice, который будет выполнять работу по вставке данных в LibreOffice, а затем в вашем питона 2,7 код envoke макро.
Поскольку макрос работает с LibreOffice, он будет использовать python3. Вот пример того, как envoke в LibreOffice макрос из командной строки:
#!/usr/bin/python3
# -*- coding: utf-8 -*-
##
# a python script to run a libreoffice python macro externally
# NOTE: for this to run start libreoffice in the following manner
# soffice "--accept=socket,host=127.0.0.1,port=2002,tcpNoDelay=1;urp;" --writer --norestore
# OR
# nohup soffice "--accept=socket,host=127.0.0.1,port=2002,tcpNoDelay=1;urp;" --writer --norestore &
#
import uno
from com.sun.star.connection import NoConnectException
from com.sun.star.uno import RuntimeException
from com.sun.star.uno import Exception
from com.sun.star.lang import IllegalArgumentException
def uno_directmacro(*args):
localContext = uno.getComponentContext()
localsmgr = localContext.ServiceManager
resolver = localsmgr.createInstanceWithContext("com.sun.star.bridge.UnoUrlResolver", localContext)
try:
ctx = resolver.resolve("uno:socket,host=localhost,port=2002;urp;StarOffice.ComponentContext")
except NoConnectException as e:
print ("LibreOffice is not running or not listening on the port given - ("+e.Message+")")
return
msp = ctx.getValueByName("/singletons/com.sun.star.script.provider.theMasterScriptProviderFactory")
sp = msp.createScriptProvider("")
scriptx = sp.getScript('vnd.sun.star.script:directmacro.py$directmacro?language=Python&location=user')
try:
scriptx.invoke((),(),())
except IllegalArgumentException as e:
print ("The command given is invalid ("+ e.Message+ ")")
return
except RuntimeException as e:
print("An unknown error occurred: " + e.Message)
return
except Exception as e:
print ("Script error ("+ e.Message+ ")")
print(e)
return
return(None)
uno_directmacro()
И это соответствующий код макроса в LibreOffice под названием «directmacro.py» и хранится в User
области для LibreOffice макросов (которые обычно составляет $ HOME/.config/LibreOffice/4/пользователь/Scripts/питон:
#!/usr/bin/python
from com.sun.star.awt.MessageBoxButtons import BUTTONS_OK, BUTTONS_OK_CANCEL, BUTTONS_YES_NO, BUTTONS_YES_NO_CANCEL, BUTTONS_RETRY_CANCEL, BUTTONS_ABORT_IGNORE_RETRY
from com.sun.star.awt.MessageBoxButtons import DEFAULT_BUTTON_OK, DEFAULT_BUTTON_CANCEL, DEFAULT_BUTTON_RETRY, DEFAULT_BUTTON_YES, DEFAULT_BUTTON_NO, DEFAULT_BUTTON_IGNORE
from com.sun.star.awt.MessageBoxType import MESSAGEBOX, INFOBOX, WARNINGBOX, ERRORBOX, QUERYBOX
def directmacro(*args):
import socket, time
class FontSlant():
from com.sun.star.awt.FontSlant import (NONE, ITALIC,)
#get the doc from the scripting context which is made available to all scripts
desktop = XSCRIPTCONTEXT.getDesktop()
model = desktop.getCurrentComponent()
text = model.Text
tRange = text.End
cursor = desktop.getCurrentComponent().getCurrentController().getViewCursor()
doc = XSCRIPTCONTEXT.getDocument()
parentwindow = doc.CurrentController.Frame.ContainerWindow
# your cannot insert simple text and text into a table with the same method
# so we have to know if we are in a table or not.
# oTable and oCurCell will be null if we are not in a table
oTable = cursor.TextTable
oCurCell = cursor.Cell
insert_text = "This is text inserted into a LibreOffice Document\ndirectly from a macro called externally"
Text_Italic = FontSlant.ITALIC
Text_None = FontSlant.NONE
cursor.CharPosture=Text_Italic
if oCurCell == None: # Are we inserting into a table or not?
text.insertString(cursor, insert_text, 0)
else:
cell = oTable.getCellByName(oCurCell.CellName)
cell.insertString(cursor, insert_text, False)
cursor.CharPosture=Text_None
return None
Вы, конечно, необходимо адаптировать код либо принять данные в качестве аргументов, прочитать из файла или любой другой.
Я попытался установить pip3 в соответствии с этой инструкцией: [ссылка] http://askubuntu.com/questions/412178/how-to-install-pip-for-python-3-in-ubuntu-12-04- LTS [/ ссылка] после этого я попробовал вашу команду PIP3 и получил эту ошибку: /USR/бен/python3 -u build.py построить – PyUsr
закончил с этой ошибкой: Command «/ USR/бен/python3 - u build.py build 'не удалось с кодом выхода 1. ------------------------------------ - Очистка ... Команда/usr/bin/python3 -c "import setuptools, tokenize; __ файл __ = '/ tmp/pip_build_root/wxPython-Phoenix/setup.py'; exec (компиляция (getattr (tokenize, ' открыть ', открыть) (__file __). read(). replace ('\ r \ n', '\ n'), __file__, 'exec')) "install --record /tmp/pip-apne5cii-record/install-record.txt - -single-version-external-managed -compile не удалось с кодом ошибки 1 в/tmp/pip_build_root/wxPython-Phoenix Сохранение журнала отладки для сбоя в /home/moddi/.pip/pip.log – PyUsr
import wx ... still и я не понимаю, почему AOO был лучше ??? Моя проблема в том, что у меня нет дистрибутива python, который импортирует uno и wx. Я не возражаю, чтобы обновить код до более нового python ... просто хочу, чтобы комбинация libs выполняла работу. – PyUsr