context manager examples

This commit is contained in:
andygoblins
2020-02-22 11:28:50 -06:00
parent f1f450cedc
commit 08af4ce9bd
2 changed files with 16 additions and 21 deletions

View File

@@ -11,15 +11,15 @@ from gnucash import Session
uri = "xml:///tmp/simple_book.gnucash"
print("uri:", uri)
ses = Session(uri, is_new=True)
book = ses.get_book()
with Session(uri, is_new=True) as ses:
book = ses.get_book()
#Call some methods that produce output to show that Book works
book.get_root_account().SetDescription("hello, book")
print("Book is saved:", not book.session_not_saved())
#Call some methods that produce output to show that Book works
book.get_root_account().SetDescription("hello, book")
print("Book is saved:", not book.session_not_saved())
print("saving...")
ses.save()
#As long as there's no exceptions, book is automatically saved
#when session ends.
print("saving...")
print("Book is saved:", not book.session_not_saved())
ses.end()

View File

@@ -19,18 +19,13 @@ except GnuCashBackendException as backend_exception:
# create a new file, this requires a file type specification
session = Session("xml://%s" % FILE_2, is_new=True)
session.save()
session.end()
session.destroy()
with Session("xml://%s" % FILE_2, is_new=True) as session:
book = session.book
root = book.get_root_account()
# open the new file, try to open it a second time, detect the lock
session = Session(FILE_2)
try:
session_2 = Session(FILE_2)
except GnuCashBackendException as backend_exception:
assert( ERR_BACKEND_LOCKED in backend_exception.errors )
session.end()
session.destroy()
with Session(FILE_2) as session:
try:
session_2 = Session(FILE_2)
except GnuCashBackendException as backend_exception:
assert( ERR_BACKEND_LOCKED in backend_exception.errors )