[Solved] Running a python script with arguments

Creating a macro - Writing a Script - Using the API (OpenOffice Basic, Python, BeanShell, JavaScript)
Post Reply
baardie
Posts: 6
Joined: Fri Dec 10, 2021 3:41 pm

[Solved] Running a python script with arguments

Post by baardie »

Hi,

I was hoping to run a script from Open Office Calc, with my script using 3 arguments that would be determined from the sheet, I have created my python script and it works via cmd I completely forgot to check on OO.
The excel sheet is used to generate barcodes, but I want to store extra data (using sheets ) as a backup but to include the date/time on it to keep a log when a # is scanned.
I would like it to be run on a form event.

Is this possible? This is my python script:

[spoiler]

Code: Select all

from __future__ import print_function
import os.path
import sys
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google.oauth2 import service_account

import datetime
# If modifying these scopes, delete the file token.json.
SCOPES = ['https://www.googleapis.com/auth/spreadsheets']
SERVICE_ACCOUNT_FILE = 'X'

id = None
product_name = ""
barcode_number = ""
creds = service_account.Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE,
                                                                  scopes=SCOPES)
        

service = build('sheets', 'v4', credentials=creds)
    
def writeValues(id, product_name, barcode_number):
    currentDate = datetime.datetime.now()
    currentTime = datetime.datetime.now()

    values = [
    [
        id, product_name, barcode_number, currentDate.strftime('%m/%d/%Y'), currentTime.strftime("%H:%M:%S")
    ],
    # Additional rows ...
    ]
    body = {
        'values': values
    }
    result = service.spreadsheets().values().append(
        spreadsheetId=SAMPLE_SPREADSHEET_ID, range=SAMPLE_RANGE_NAME,
        valueInputOption="USER_ENTERED", body=body).execute()
    print('{0} cells appended.'.format(result
                                   .get('updates')
                                   .get('updatedCells')))

# The ID and range of a sample spreadsheet.
SAMPLE_SPREADSHEET_ID = 'X'
SAMPLE_RANGE_NAME = 'Sheet1!A1:D'


def main():
    id = int(sys.argv[1])
    product_name = str(sys.argv[2])
    bardcode_number1 = str(sys.argv[3])
    writeValues(id, product_name, bardcode_number1)
    print ('Number of arguments:', len(sys.argv), 'arguments.')
    print ('Argument List:', str(sys.argv))
  

    # Call the Sheets API
    sheet = service.spreadsheets()
    
if __name__ == '__main__':
    main()
[/spoiler]
Last edited by baardie on Tue Dec 14, 2021 1:54 pm, edited 1 time in total.
OpenOffice 4.1.11 on Windows 10
baardie
Posts: 6
Joined: Fri Dec 10, 2021 3:41 pm

Re: Running a python script with arguments

Post by baardie »

Or if possible, just save cells a1-a4 and append that data to a different file?
OpenOffice 4.1.11 on Windows 10
baardie
Posts: 6
Joined: Fri Dec 10, 2021 3:41 pm

Re: Running a python script with arguments

Post by baardie »

For reference, I need to bascially output this data somewhere else e.g a db or another worksheet. This sheet is not used for saving but is just kept open to generate codes to print - and we just want to grab that info and save it. It currently uses a text box event that triggers a vba macro to print the selection

Image
OpenOffice 4.1.11 on Windows 10
User avatar
Villeroy
Volunteer
Posts: 31279
Joined: Mon Oct 08, 2007 1:35 am
Location: Germany

Re: Running a python script with arguments

Post by Villeroy »

Why do you post screenshots? This makes absolutely no sense. Post documents!
Please, edit this topic's initial post and add "[Solved]" to the subject line if your problem has been solved.
Ubuntu 18.04 with LibreOffice 6.0, latest OpenOffice and LibreOffice
User avatar
karolus
Volunteer
Posts: 1160
Joined: Sat Jul 02, 2011 9:47 am

Re: Running a python script with arguments

Post by karolus »

baardie wrote:For reference, I need to bascially output this data somewhere else e.g a db or another worksheet. This sheet is not used for saving but is just kept open to generate codes to print - and we just want to grab that info and save it. It currently uses a text box event that triggers a vba macro to print the selection
So far, your problem is absolutly unrelated to the generated Spreadsheet-dokument, so you should backup the data wherever you want from the python-script itself
AOO4, Libreoffice 6.1 on Rasbian OS (on ARM)
Libreoffice 7.4 on Debian 12 (Bookworm) (on RaspberryPI4)
Libreoffice 7.6 flatpak on Debian 12 (Bookworm) (on RaspberryPI4)
baardie
Posts: 6
Joined: Fri Dec 10, 2021 3:41 pm

Re: Running a python script with arguments

Post by baardie »

karolus wrote:
baardie wrote:For reference, I need to bascially output this data somewhere else e.g a db or another worksheet. This sheet is not used for saving but is just kept open to generate codes to print - and we just want to grab that info and save it. It currently uses a text box event that triggers a vba macro to print the selection
So far, your problem is absolutly unrelated to the generated Spreadsheet-dokument, so you should backup the data wherever you want from the python-script itself
Yes, the issue is I need to be able to read certain cells within the current open one and append certain cell ranges to a csv but unsure of the process. The file that has the data is .ods

Or realistically, would it be easier to use an external mysql db or I could use base?
OpenOffice 4.1.11 on Windows 10
baardie
Posts: 6
Joined: Fri Dec 10, 2021 3:41 pm

Re: Running a python script with arguments

Post by baardie »

Righty, I made the thread a mess because I didn't have a proper look at what was available, my apologies.

Instead of python, I have tried to go for just a basic macro - connect to registered base db, grab the cell value and insert into db.

It finds the registered DB and the SQL command executes but the db doesn't reflect. If I rename some things it even compains about the table already being made?

Code: Select all

 oDBCntxt = CreateUnoService("com.sun.star.sdb.DatabaseContext")
  oDBSrc = oDBCntxt.getByName( "test" )
  oConnection = oDBSrc.getConnection("","")
  oStatement = oConnection.CreateStatement

Dim Doc As Object
Dim Sheet As Object
Dim Cell As Object
Dim CellString as String

Doc = ThisComponent
ThisComponent.calculateAll
Sheet = Doc.Sheets(0)

Cell = Sheet.getCellByPosition(0, 1)
CellString = Cell.getValue()

sSQL =        "drop table Table31 if exists; "
  sSQL = sSQL & "create table Table31 (ID int IDENTITY, barcode char(50), timedate char(50) );"
  
sSQL = sSQL + "insert into Table31 ( barcode, timedate ) values('" + CellString + "1', '55gg');"
  oStatement.execute( sSQL)
OpenOffice 4.1.11 on Windows 10
User avatar
Villeroy
Volunteer
Posts: 31279
Joined: Mon Oct 08, 2007 1:35 am
Location: Germany

Re: Running a python script with arguments

Post by Villeroy »

You can use form controls on sheets and link them to your database.
viewtopic.php?t=88516&p=416210#p416210
Please, edit this topic's initial post and add "[Solved]" to the subject line if your problem has been solved.
Ubuntu 18.04 with LibreOffice 6.0, latest OpenOffice and LibreOffice
User avatar
Villeroy
Volunteer
Posts: 31279
Joined: Mon Oct 08, 2007 1:35 am
Location: Germany

Re: [Solved] Running a python script with arguments

Post by Villeroy »

And this is a simple Python macro where I tried my best to convert sheet cell data to database data in order to enable a transfer from Calc to Base: Base, Calc, Python: INSERT, UPDATE, DELETE from spreadsheet
Please, edit this topic's initial post and add "[Solved]" to the subject line if your problem has been solved.
Ubuntu 18.04 with LibreOffice 6.0, latest OpenOffice and LibreOffice
baardie
Posts: 6
Joined: Fri Dec 10, 2021 3:41 pm

Re: Running a python script with arguments

Post by baardie »

Villeroy wrote:You can use form controls on sheets and link them to your database.
viewtopic.php?t=88516&p=416210#p416210
Apologies,

I have ended up attaching a registered base .odb and it works using sql now but it locks the file and it creates a new file per PC e.g if two pc's run the script it one will continue to use the original and the other will create mydatabase.PCNAMEHERE

Edit: Changed to my online sql server working fine so far! Thank you Villeroy
OpenOffice 4.1.11 on Windows 10
Post Reply