How to create transaction in GnuCash in response to an email

0 votes

I would like to create a script which is triggered by an email filter which, when run, creates two transactions in GnuCash. I see that GnuCash has Python bindings but the documentation is sparse at best... a better term would be "nonexistent".

Is it possible to write a script which will create transactions in GnuCash? If so, what would the very basic code look like? I just need a starting point; once I have that I can script this fairly well myself.

Sep 5, 2018 in Python by bug_seeker
• 15,520 points
982 views

1 answer to this question.

0 votes

Here's a template, along with a couple of account lookup functions which are sorely lacking in the library. You can place all of the transaction code into a function, then hand in whatever data you need to create the two custom transactions. Then just call the transaction function from your email listener, and you should be in business.

from gnucash import Session, Account, Transaction, Split, GncNumeric
import gnucash
from datetime import datetime

def lookup_account_by_path(parent, path):
    acc = parent.lookup_by_name(path[0])
    if acc.get_instance() == None:
        raise Exception('Account path {} not found'.format(':'.join(path)))
    if len(path) > 1:
        return lookup_account_by_path(acc, path[1:])
    return acc

def lookup_account(root, name):
    path = name.split(':')
    return lookup_account_by_path(root, path)

session = Session("/path/to/file.gnucash") #, ignore_lock=True)
   # or use URI string: ('mysql://USER:PASSWORD@HOST/DATABASE')

today = datetime.now()
book = session.book # All actions are performed through the book object (or its children)
root = book.get_root_account() # Parent of all accounts
currency = book.get_table().lookup('ISO4217', "USD")
tx = Transaction(book)
tx.BeginEdit()
tx.SetCurrency(currency)
tx.SetDateEnteredTS(today)
tx.SetDatePostedTS(today) # or another datetime object for the transaction's "register date"
tx.SetDescription("Transaction Description!")
#tx.SetNum(int_variable) # if you need a transaction number

sp1 = Split(book) # First half of transaction
sp1.SetParent(tx)
# The lookup string needs to match your account path exactly.
sp1.SetAccount(lookup_account(root, "Expenses:Some Expense Account"))
# amount is an int (no $ or .), so $5.23 becomes amount=523
sp1.SetValue(GncNumeric(amount, 100)) # Assuming you only have one split
# For multiple splits, you need to make sure the totals all balance out.
sp1.SetAmount(GncNumeric(amount, 100))
sp1.SetMemo("Split Memo!") # optional

sp2 = Split(book) # Need a balancing split
sp2.SetParent(tx)
sp2.SetAccount(lookup_account(root, "Assets:Current Assets:Checking"))
sp2.SetValue(sp1.GetValue().neg())
sp2.SetAmount(sp1.GetValue().neg())
sp2.SetMemo("Other Split Memo!") # optional

tx.CommitEdit() # Finish editing transaction
session.save()
session.end()
answered Sep 5, 2018 by Priyaj
• 58,100 points

Related Questions In Python

+4 votes
7 answers
+1 vote
5 answers

how to exit a python script in an if statement

Instead of using the normal UTF-8 encoding, ...READ MORE

answered Jul 4, 2023 in Python by bodymist
• 140 points
354,380 views
0 votes
1 answer

How to break for loop in an if statement

You can break out of each loop ...READ MORE

answered Nov 16, 2018 in Python by Jino
• 5,820 points
2,934 views
0 votes
1 answer

How to correctly return an a dictionary as an output in zappier code using python?

David here, from the Zapier Platform team. ...READ MORE

answered Dec 3, 2018 in Python by charlie_brown
• 7,720 points
1,567 views
0 votes
2 answers
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 4,344 views
0 votes
1 answer
+1 vote
1 answer

How to create plots using python matplotlib in IPython notebook?

I think you should try: I used %matplotlib inline in ...READ MORE

answered Aug 8, 2018 in Python by Priyaj
• 58,100 points
1,454 views
+1 vote
1 answer

How to print an error in Python?

For Python 2.6 and later and Python ...READ MORE

answered Aug 23, 2018 in Python by Priyaj
• 58,100 points
1,385 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP