LibreOffice Calc & Python Programming: Part 4 – using (APSO) console to print text.

In this episode of my LibreOffice Calc & Python Programming tutorial series I am going to show a quick way to display text in order to watch some variables or to debug programs.

Display text with the console

Sometimes (actually quite often!) you get error messages when trying to execute a program. Sometimes it’s easy to fix, sometimes not. It always helps to understand why the error is happening even if you don’t understand what the error message means.
If it’s a syntax error, you just need to change a key word in the program. When it’s a problem with one of the parameter of a function it’s usually because that parameter is not meant to be used by the function, and it is really useful to see how that parameter looks like using a print statement to display that parameter on a console.

If you have installed the Add-on APSO, then like in many other programming languages to display the value of a parameter at runtime you just do a print(x) and the value of x is display in a console.

So let’s add a print in our main program that is triggered with a button (see Part 2):

def main(*args):
    """Our main program, that call other functions in the order we want"""
    write_my_text("My first macro in Python!")
    print("All done!")

If you run the program without having the APSO console on, you won’t see anything.

Use the console:

To find the APSO console, go in Tools/Macro/Organize Python scripts.
If you can’t see this menu, it probably means that you have not installed the APSO add-on (again find how to install the APSO add-on ). From the Python scripts Organiser, click on ‘Menu’ then ‘Python Shell’.

There’s the APSO Python Shell..

So after that you have pressed the button that triggers our program main you will see in the Python Shell:

All done!

Let’s now use the console for checking a variable.

Let’s edit our ‘write_1_to_10()’ function that we wrote in part 3 of this series of tutorials and add a print to watch the loop’s progress in the console:

def write_1_to_10():
    """Write what I want in in Cell A1"""
    for each_number in range(10):
        print("loop at: ", each_number)        
        active_sheet.getCellByPosition(1,each_number).Value = each_number + 1

We’ve added the line:
print("loop at:", each_number)
The instruction print is used here with a string “loop at: “and the variable each_number and will help us to see how that variable behave in the loop we have written without needing to display it into a LibreOffice cell.
Once you’ve run the main program you should be able to see in your console:

Loop and final text…

Quick and easy! However let me know if you have any problem, and any other comments are welcome too.

Leave a Comment

Your email address will not be published. Required fields are marked *