-2

Update acknowledging comment 1 and 4: Indentation corrected, does compile in Geany, obvious redundancies stripped.

The first question is: why am I getting the args error when I try to run my code? The error message refers to a LO file.... (linux) /opt/libreoffice7.2/programs/pythonscript.py @ line 915. An excerpt from that file says...

    def invoke(self, args, out, outindex ):                # 910
        log.debug( "PythonScript.invoke " + str( args ) )  # 911
        try:                                               # 912
            if (self.args):                                # 913
                args += self.args                          # 915
            ret = self.func( *args )                       # 915

My code is...

# -*- coding: UTF-8 -*-
from __future__ import unicode_literals

# Gets the current document
doc = XSCRIPTCONTEXT.getDocument()
ctx = XSCRIPTCONTEXT.getComponentContext()
sm = CTX.ServiceManager

import time
import datetime
import serial
import openpyxl


def PySerLO (args=None):
    from datetime import date
    from openpyxl import load_workbook
    ser = serial.Serial('/dev/ttyUSB0') # ""ls /dev/ttyUSB* -l"" if unsure. 

# Load the workbook and select the sheet...
    wb = load_workbook('/media/mpa/UserFiles/LibreOffice/mpaNEW-spreadsheet.xlsx')
    sheet = wb['Sheet1']
    headings = ("Date", "Time", "Raw Data")
    sheet.append(headings)
    
    try:
        while True:
            # Get current date, Get current time, Read the serial port
            today = date.today()
            now = datetime.datetime.now().time()
            data = ser.readline().decode()
            if data != "":
                row = (today, now, float((data)))   # For some reason the first data point is garbage so don't do anything with this
                row = (today, ("%s"%now), float((data)))
                sheet.append(row)
                ser.flush()
                #Save the workbook to preserve data 
                wb.save('/media/mpa/UserFiles/LibreOffice/mpaNEW-spreadsheet.xlsx')

    finally:
        # Make sure the workbook is saved at end
        wb.save('/media/mpa/UserFiles/LibreOffice/mpaNEW-spreadsheet.xlsx')
        print('Data Finished')

I get this error on executing a macro executing command button...

enter image description here

I appreciate your patience and suggestions on improvement thus far.

The ultimate aim of this is to track and instantly plot scientific data, introduce my students to the power of LibreOffice - They download LO and I just pass them the fully contained spreadsheet. They then connect the hardware and they have an excellent resource on LO forever. Almost none of them have ever heard of LibreOffice (or Linux either!)

Micklos
  • 97
  • 9
  • 1
    Welcome to [Stack Overflow.](https://stackoverflow.com/ "Stack Overflow") Please be aware this is not a code-writing or tutoring service. We can help solve specific, technical problems, not open-ended requests for code or advice. Please edit your question to show what you have tried so far, and what specific problem you need help with. See the [How To Ask a Good Question](https://stackoverflow.com/help/how-to-ask "How To Ask a Good Question") page for details on how to best help us help you. – itprorh66 Jan 01 '22 at 14:04
  • "Will my args have to match the data" - Python uses duck typing, meaning that variables are not declared with a type, so I think the answer is no. Beyond that, I'm not sure what your question is asking. Are you looking for a tutorial? There is one at http://christopher5106.github.io/office/2015/12/06/openoffice-libreoffice-automate-your-office-tasks-with-python-macros.html. – Jim K Jan 01 '22 at 14:36
  • @Jim K. Yes kind of what Christopher was advising at the "Pack your script inside the document : the OpenDocument format" part. but I struggled to fully pick up on all the code that was in his script for embedding and wanted to avoid unzipping, attaching files and re-zipping as there seemed more partial references to doing it directly with APSO and it seemed more efficient, but using ODS format would probaby kill openpyxl functionality. – Micklos Jan 01 '22 at 16:23
  • I've read your edited question a couple of times but cannot follow it. You are asking way too many things at once, and the code is a mess. It doesn't even look like it would compile - the indentation seems incorrect for one thing. Maybe `PySerLO` is the entry point called when a button is clicked? But there are lots of other things going on outside of or around that function. Work on it some more until it's clean and straightforward and then probably delete this question and post a simpler one. "can I just use it inside..." - not sure what this means; use what inside where? – Jim K Jan 01 '22 at 17:24
  • You could also post at ask.libreoffice.org, where they are more willing to work with questions that aren't very clear, and will try to guess what you might be trying to do. – Jim K Jan 01 '22 at 17:25
  • @ Jim K. Thanks for advise on helping me clean up the code. I've edited it again. Hopefully its more digestible now :) – Micklos Jan 02 '22 at 00:15
  • post the full error message – diggusbickus Jan 02 '22 at 00:16
  • @diggusbickus ;) I included a pic of the graphic of the end of my original post. If it will be helpful I can type the whole thing out. – Micklos Jan 02 '22 at 01:53
  • this is not a python error message. was the script working before using it as a macro? maybe you should start here – diggusbickus Jan 02 '22 at 02:00
  • @ diggusbickus. The code is a modified version of a fully working .py file which I used to run from the command line - i..e just running the .py file. It used to have debugging print statements inside of it giving me a better idea as to when to terminate it (with CTRL+C) but I really need to have the sheet open for be to do live charting and data control via Form Control elements, hence me wanting to embed the python code (Couldn't make any progress using LO's internal Basic). I can do everything in Excel but I want to move to Linux(done) and LO (trying to do here) as I believe in FOSS. – Micklos Jan 02 '22 at 04:28
  • I'm not sure how it isn't a python message as it refers to coding in the pythonscript.py file. It's the only error message I get at the moment. – Micklos Jan 02 '22 at 04:33

1 Answers1

1

First of all, I do not think you should start by embedding the macro in the document. I don't think it is required for the reasons you seem to believe. Instead, put your code in My Macros (the LibreOffice user directory) where it is easier to develop. Then call it from a button or by going to Tools > Macros > Run Macro - no need to use APSO as it seems like that is causing you even more confusion. The only reason for embedding is for convenience, to make it easier to keep the document and a bit of code together. For complex code that needs to be given to multiple people, it's generally better to create a full-fledged extension.

Second, it looks like the error may be from M1.py line 22 - is this your code? I cannot tell where line 22 might be or where exactly the error is coming from. Most of us reading your question are looking for the code where the error message comes from, but we cannot find it because you did not provide the relevant file name or line number of your code. It is your job to simplify your code enough so that you can see where the error is coming from, and then give that information in the question.

The error mentions create_instance which is the call for creating an UNO service.

Also I am not comfortable with the idea of storing XSCRIPTCONTEXT values in global variables unless you're sure you know what you're doing (and it's pretty clear you don't. :) )

Also I have strong doubts about achieving success by combining different libraries - it looks like you want to use both openpyxl and the UNO interface in the same code, and I would not expect that to turn out well. Just stick with plain UNO because there are plenty of people who can help with that. (Or if you choose openpyxl then I will ignore your question and someone knowledgeable about that may be able to help.)

Finally, it seems like import uno is missing. That alone could explain the error, and it's hard to imagine how you have all this code yet didn't even start with that.

Before trying all of this complex code, get a simple example working. It looks like there are a lot of python-uno fundamentals you still need to figure out first, and it doesn't look like you have put much effort into working through a tutorial yet.

E_net4
  • 27,810
  • 13
  • 101
  • 139
Jim K
  • 12,824
  • 2
  • 22
  • 51