gnucash unstable: More python 3 fixups.
John Ralls
jralls at code.gnucash.org
Thu Mar 22 18:20:06 EDT 2018
Updated via https://github.com/Gnucash/gnucash/commit/bea89a50 (commit)
from https://github.com/Gnucash/gnucash/commit/f05bbe24 (commit)
commit bea89a50ac0656c229c0ec6e54053fc08563397c
Author: John Ralls <jralls at ceridwen.us>
Date: Thu Mar 22 15:08:22 2018 -0700
More python 3 fixups.
diff --git a/bindings/python/example_scripts/account_analysis.py b/bindings/python/example_scripts/account_analysis.py
index dd7fc4a..87e1dfe 100644
--- a/bindings/python/example_scripts/account_analysis.py
+++ b/bindings/python/example_scripts/account_analysis.py
@@ -152,13 +152,13 @@ def account_from_path(top_account, account_path, original_path=None):
def main():
if len(argv) < 10:
- print 'not enough parameters'
- print 'usage: account_analysis.py {book url} {start year} {start month, numeric} {period type: monthly, quarterly, or yearly} {number of periods to show, from start year and month} {whether to show debits: debits-show for true, all other values false} {whether to show credits: credits-show for true, all other values false} {space separated account path, as many nested levels as desired} '
- print 'examples:\n'
- print "The following example analyzes 12 months of 'Assets:Test Account' from /home/username/test.gnucash, starting in January of 2010, and shows both credits and debits"
- print "gnucash-env python account_analysis.py '/home/username/test.gnucash' 2010 1 monthly 12 debits-show credits-show Assets 'Test Account'\n"
- print "The following example analyzes 2 quarters of 'Liabilities:First Level:Second Level' from /home/username/test.gnucash, starting March 2011, and shows credits but not debits"
- print "gnucash-env python account_analysis.py '/home/username/test.gnucash' 2011 3 quarterly 2 debits-noshow credits-show Liabilities 'First Level' 'Second Level"
+ print('not enough parameters')
+ print('usage: account_analysis.py {book url} {start year} {start month, numeric} {period type: monthly, quarterly, or yearly} {number of periods to show, from start year and month} {whether to show debits: debits-show for true, all other values false} {whether to show credits: credits-show for true, all other values false} {space separated account path, as many nested levels as desired} ')
+ print('examples:\n')
+ print("The following example analyzes 12 months of 'Assets:Test Account' from /home/username/test.gnucash, starting in January of 2010, and shows both credits and debits")
+ print("gnucash-env python account_analysis.py '/home/username/test.gnucash' 2010 1 monthly 12 debits-show credits-show Assets 'Test Account'\n")
+ print("The following example analyzes 2 quarters of 'Liabilities:First Level:Second Level' from /home/username/test.gnucash, starting March 2011, and shows credits but not debits")
+ print("gnucash-env python account_analysis.py '/home/username/test.gnucash' 2011 3 quarterly 2 debits-noshow credits-show Liabilities 'First Level' 'Second Level")
return
try:
diff --git a/bindings/python/example_scripts/gncinvoice_jinja.py b/bindings/python/example_scripts/gncinvoice_jinja.py
index 6e4eaff..ec93ed0 100644
--- a/bindings/python/example_scripts/gncinvoice_jinja.py
+++ b/bindings/python/example_scripts/gncinvoice_jinja.py
@@ -39,8 +39,8 @@ try:
import jinja2
from gncinvoicefkt import *
except ImportError as import_error:
- print "Problem importing modules."
- print import_error
+ print("Problem importing modules.")
+ print(import_error)
sys.exit(2)
class Usage(Exception):
@@ -68,26 +68,26 @@ def main(argv=None):
for opt in opts:
if opt[0] in ["-f"]:
- print "ignoring lock"
+ print("ignoring lock")
ignore_lock = True
if opt[0] in ["-h","--help"]:
raise Usage("Help:")
if opt[0] in ["-I"]:
invoice_id = opt[1]
- print "using invoice ID '" + str(invoice_id) + "'."
+ print("using invoice ID '" + str(invoice_id) + "'.")
if opt[0] in ["-o"]:
filename_output = opt[1]
- print "using output file", filename_output
+ print("using output file", filename_output)
if opt[0] in ["-t"]:
filename_template = opt[1]
- print "using template file", filename_template
+ print("using template file", filename_template)
if opt[0] in ["-l"]:
list_invoices = True
- print "listing invoices"
+ print("listing invoices")
# Check for correct input
if len(args)>1:
- print "opts:",opts,"args:",args
+ print("opts:",opts,"args:",args)
raise Usage("Only one input possible !")
if len(args)==0:
raise Usage("No input given !")
@@ -103,41 +103,41 @@ def main(argv=None):
if not filename_output:
if filename_template:
filename_output = filename_template + ".out"
- print "no output filename given, will be:", filename_output
+ print("no output filename given, will be:", filename_output)
except Usage, err:
if err.msg == "Help:":
retcode=0
else:
- print >>sys.stderr, "Error:",err.msg
- print >>sys.stderr, "for help use --help"
+ print(>>sys.stderr, "Error:",err.msg)
+ print(>>sys.stderr, "for help use --help")
retcode=2
- print
- print "Usage:"
- print
- print "Invoke with",prog_name,"gnucash_url."
- print "where input is"
- print " filename"
- print "or file://filename"
- print "or mysql://user:password@host/databasename"
- print
- print "-f force open = ignore lock"
- print "-l list all invoices"
- print "-h or --help for this help"
- print "-I ID use invoice ID"
- print "-t filename use filename as template file"
- print "-o filename use filename as output file"
+ print()
+ print("Usage:")
+ print()
+ print("Invoke with",prog_name,"gnucash_url.")
+ print("where input is")
+ print(" filename")
+ print("or file://filename")
+ print("or mysql://user:password@host/databasename")
+ print()
+ print("-f force open = ignore lock")
+ print("-l list all invoices")
+ print("-h or --help for this help")
+ print("-I ID use invoice ID")
+ print("-t filename use filename as template file")
+ print("-o filename use filename as output file")
return retcode
# Try to open the given input
try:
- print "Opening", input_url, "."
+ print("Opening", input_url, ".")
session = gnucash.Session(input_url, ignore_lock=ignore_lock)
except Exception as exception:
- print "Problem opening input."
- print exception
+ print("Problem opening input.")
+ print(exception)
return 2
book = session.book
@@ -149,22 +149,22 @@ def main(argv=None):
if list_invoices:
for number,invoice in enumerate(invoice_list):
- print str(number)+")"
- print invoice
+ print(str(number)+")")
+ print(invoice)
if not (no_output):
if invoice_id:
invoice = book.InvoiceLookupByID(invoice_id)
if not invoice:
- print "ID not found."
+ print("ID not found.")
return 2
if invoice_number:
invoice = invoice_list[invoice_number]
- print "Using the following invoice:"
- print invoice
+ print("Using the following invoice:")
+ print(invoice)
loader = jinja2.FileSystemLoader('.')
env = jinja2.Environment(loader=loader)
@@ -174,7 +174,7 @@ def main(argv=None):
#IPython.embed()
output = template.render(invoice=invoice, locale=locale)
- print "Writing output", filename_output, "."
+ print("Writing output", filename_output, ".")
with open(filename_output, 'w') as f:
f.write(output.encode('utf-8'))
diff --git a/bindings/python/example_scripts/gncinvoicefkt.py b/bindings/python/example_scripts/gncinvoicefkt.py
index 9e0ffa0..ef778b4 100644
--- a/bindings/python/example_scripts/gncinvoicefkt.py
+++ b/bindings/python/example_scripts/gncinvoicefkt.py
@@ -1,5 +1,5 @@
#!/usr/bin/env python
-# -*- coding: UTF-8 -*-
+# -*- coding: utf-8 -*-
##@file
# @brief some help for working with invoices, used in \ref py_invoice_export
@@ -22,8 +22,8 @@ try:
GNC_DISC_PRETAX
import str_methods
except ImportError as import_error:
- print "Problem importing modules."
- print import_error
+ print("Problem importing modules.")
+ print(import_error)
sys.exit(2)
def get_all_lots(account):
diff --git a/bindings/python/example_scripts/latex_invoices.py b/bindings/python/example_scripts/latex_invoices.py
index 8b738fa..4c6c1d4 100644
--- a/bindings/python/example_scripts/latex_invoices.py
+++ b/bindings/python/example_scripts/latex_invoices.py
@@ -1,5 +1,5 @@
#!/usr/bin/env python
-# -*- coding: UTF-8 -*-
+# -*- coding: utf-8 -*-
##@file
# @brief Exports an invoice to lco-file for use with LaTeX, see \ref py_invoice_export
@@ -66,8 +66,8 @@ try:
GNC_DISC_PRETAX
import locale
except ImportError as import_error:
- print "Problem importing modules."
- print import_error
+ print("Problem importing modules.")
+ print(import_error)
sys.exit(2)
class Usage(Exception):
@@ -157,7 +157,7 @@ def invoice_to_lco(invoice):
line_str += uprice
line_str += u"}"
- #print line_str
+ #print(line_str)
ent_str += line_str
lco_out += write_variable("entries",ent_str)
@@ -184,25 +184,25 @@ def main(argv=None):
for opt in opts:
if opt[0] in ["-f"]:
- print "ignoring lock"
+ print("ignoring lock")
ignore_lock = True
if opt[0] in ["-h","--help"]:
raise Usage("Help:")
if opt[0] in ["-i"]:
- print "Using ipshell"
+ print("Using ipshell")
with_ipshell = True
if opt[0] in ["-l"]:
- print "listing all invoices"
+ print("listing all invoices")
list_invoices=True
if opt[0] in ["-n"]:
invoice_number = int(opt[1])
- print "using invoice number", invoice_number
+ print("using invoice number", invoice_number)
no_latex_output = False
if opt[0] in ["-o"]:
output_file_name = opt[1]
- print "using output file", output_file_name
+ print("using output file", output_file_name)
if len(args)>1:
- print "opts:",opts,"args:",args
+ print("opts:",opts,"args:",args)
raise Usage("Only one input can be accepted !")
if len(args)==0:
raise Usage("No input given !")
@@ -211,26 +211,26 @@ def main(argv=None):
if err.msg == "Help:":
retcode=0
else:
- print >>sys.stderr, "Error:",err.msg
- print >>sys.stderr, "for help use --help"
+ print(>>sys.stderr, "Error:",err.msg)
+ print(>>sys.stderr, "for help use --help")
retcode=2
- print "Generate a LaTeX invoice or print out all invoices."
- print
- print "Usage:"
- print
- print "Invoke with",prog_name,"input."
- print "where input is"
- print " filename"
- print "or file://filename"
- print "or mysql://user:password@host/databasename"
- print
- print "-f force open = ignore lock"
- print "-h or --help for this help"
- print "-i for ipython shell"
- print "-l list all invoices"
- print "-n number use invoice number (no. from previous run with -l)"
- print "-o name use name as outputfile. default: data.lco"
+ print("Generate a LaTeX invoice or print out all invoices.")
+ print()
+ print("Usage:")
+ print()
+ print("Invoke with",prog_name,"input.")
+ print("where input is")
+ print(" filename")
+ print("or file://filename")
+ print("or mysql://user:password@host/databasename")
+ print()
+ print("-f force open = ignore lock")
+ print("-h or --help for this help")
+ print("-i for ipython shell")
+ print("-l list all invoices")
+ print("-n number use invoice number (no. from previous run with -l)")
+ print("-o name use name as outputfile. default: data.lco")
return retcode
@@ -238,8 +238,8 @@ def main(argv=None):
try:
session = gnucash.Session(input_url,ignore_lock=ignore_lock)
except Exception as exception:
- print "Problem opening input."
- print exception
+ print("Problem opening input.")
+ print(exception)
return 2
book = session.book
@@ -251,18 +251,18 @@ def main(argv=None):
if list_invoices:
for number,invoice in enumerate(invoice_list):
- print str(number)+")"
- print invoice
+ print(str(number)+")")
+ print(invoice)
if not (no_latex_output):
if invoice_number == None:
- print "Using the first invoice:"
+ print("Using the first invoice:")
invoice_number=0
invoice=invoice_list[invoice_number]
- print "Using the following invoice:"
- print invoice
+ print("Using the following invoice:")
+ print(invoice)
lco_str=invoice_to_lco(invoice)
diff --git a/bindings/python/example_scripts/new_book_with_opening_balances.py b/bindings/python/example_scripts/new_book_with_opening_balances.py
index 08a08de..0ee02c4 100644
--- a/bindings/python/example_scripts/new_book_with_opening_balances.py
+++ b/bindings/python/example_scripts/new_book_with_opening_balances.py
@@ -290,11 +290,11 @@ def create_opening_balance_transaction(commodtable, namespace, mnemonic,
def main():
if len(argv) < 3:
- print 'not enough parameters'
- print 'usage: new_book_with_opening_balances.py {source_book_url} {destination_book_url}'
- print 'examples:'
- print "gnucash-env python new_book_with_opening_balances.py '/home/username/test.gnucash' 'sqlite3:///home/username/new_test.gnucash'"
- print "gnucash-env python new_book_with_opening_balances.py '/home/username/test.gnucash' 'xml:///crypthome/username/finances/new_test.gnucash'"
+ print('not enough parameters')
+ print('usage: new_book_with_opening_balances.py {source_book_url} {destination_book_url}')
+ print('examples:')
+ print("gnucash-env python new_book_with_opening_balances.py '/home/username/test.gnucash' 'sqlite3:///home/username/new_test.gnucash'")
+ print("gnucash-env python new_book_with_opening_balances.py '/home/username/test.gnucash' 'xml:///crypthome/username/finances/new_test.gnucash'")
return
#have everything in a try block to unable us to release our hold on stuff to the extent possible
diff --git a/bindings/python/example_scripts/priceDB_test.py b/bindings/python/example_scripts/priceDB_test.py
index fcd30e2..41f42fb 100644
--- a/bindings/python/example_scripts/priceDB_test.py
+++ b/bindings/python/example_scripts/priceDB_test.py
@@ -41,11 +41,11 @@ for pr in pl:
time = pr.get_time()
v=pr.get_value()
price = float(v.num)/v.denom
- print time, source, price
+ print(time, source, price)
if len(pl) > 0:
v0 = pl[0].get_value()
- print arm.get_fullname(), float(v0.num) / float(v0.denom )
+ print(arm.get_fullname(), float(v0.num) / float(v0.denom ))
session.end()
session.destroy()
diff --git a/bindings/python/example_scripts/price_database_example.py b/bindings/python/example_scripts/price_database_example.py
index 86db033..b9b10e8 100755
--- a/bindings/python/example_scripts/price_database_example.py
+++ b/bindings/python/example_scripts/price_database_example.py
@@ -57,12 +57,12 @@ for namespace in namespaces:
if len(commodities) == 0 :
- print "No commodity in namespace "+namespace_name+"."
+ print("No commodity in namespace "+namespace_name+".")
else:
if commodity_fullname:
- print "Searching commodity '"+commodity_fullname+"' in namespace "+namespace_name
+ print("Searching commodity '"+commodity_fullname+"' in namespace "+namespace_name)
else:
- print "Commoditys in namespace "+namespace_name+":"
+ print("Commoditys in namespace "+namespace_name+":")
for i, c in enumerate(commodities):
@@ -70,12 +70,12 @@ for namespace in namespaces:
c_fullname = c.get_fullname()
if not(commodity_fullname) or (commodity_fullname == c_fullname):
- print "["+str(i)+"] Full Name :", c.get_fullname()
+ print("["+str(i)+"] Full Name :", c.get_fullname())
if show_prices:
pl = pdb.get_prices(c,cur)
if len(pl) > 0 :
- print "{0} {1:20}{2:>10} {3}".format("Time ","Source","Price","Currency")
+ print("{0} {1:20}{2:>10} {3}".format("Time ","Source","Price","Currency"))
for pr in pl:
source = pr.get_source()
@@ -83,7 +83,7 @@ for namespace in namespaces:
v=pr.get_value()
price = float(v.num)/v.denom
- print "{0} {1:20}{2:10.4f} {3}".format(time,source,price,cur_name)
+ print("{0} {1:20}{2:10.4f} {3}".format(time,source,price,cur_name))
# I didn't find out how to format the time option...
session.end()
diff --git a/bindings/python/example_scripts/quotes_historic.py b/bindings/python/example_scripts/quotes_historic.py
index da70cc7..964c70f 100644
--- a/bindings/python/example_scripts/quotes_historic.py
+++ b/bindings/python/example_scripts/quotes_historic.py
@@ -60,14 +60,14 @@ stock = ac.GetCommodity()
# Add the prices
pdb = book.get_price_db()
if len(ac.GetSplitList())<1:
- print 'Need at least one Split to get currency info ... '
+ print('Need at least one Split to get currency info ... ')
raise SystemExit
cur = ac.GetSplitList()[0].GetParent().GetCurrency()
# Get stock data
pl = pdb.get_prices(stock,cur)
if len(pl)<1:
- print 'Need at least one database entry to clone ...'
+ print('Need at least one database entry to clone ...')
raise SystemExit
pl0 = pl[0]
@@ -77,7 +77,7 @@ for i in range(1,len(pl)):
for i in range(0,len(stock_date)):
p_new = pl0.clone(book)
p_new = gnucash.GncPrice(instance=p_new)
- print 'Adding',i,stock_date[i],stock_price[i]
+ print('Adding',i,stock_date[i],stock_price[i])
p_new.set_time(stock_date[i])
v = p_new.get_value()
v.num = int(Fraction.from_float(stock_price[i]).limit_denominator(100000).numerator)
diff --git a/bindings/python/example_scripts/rest-api/gnucash_rest.py b/bindings/python/example_scripts/rest-api/gnucash_rest.py
index f6a4dc9..5444b98 100644
--- a/bindings/python/example_scripts/rest-api/gnucash_rest.py
+++ b/bindings/python/example_scripts/rest-api/gnucash_rest.py
@@ -835,7 +835,7 @@ def getAccountsFlat(book):
for n, account in enumerate(flat_accounts):
if account['type_id'] in type_ids:
filtered_flat_account.append(account)
- print account['name'] + ' ' + str(account['type_id'])
+ print(account['name'] + ' ' + str(account['type_id']))
return filtered_flat_account
@@ -1846,7 +1846,7 @@ def shutdown():
session.save()
session.end()
session.destroy()
- print 'Shutdown'
+ print('Shutdown')
class Error(Exception):
"""Base class for exceptions in this module."""
@@ -1858,12 +1858,12 @@ class Error(Exception):
try:
options, arguments = getopt.getopt(sys.argv[1:], 'nh:', ['host=', 'new='])
except getopt.GetoptError as err:
- print str(err) # will print something like "option -a not recognized"
- print 'Usage: python-rest.py <connection string>'
+ print(str(err) # will print something like "option -a not recognized")
+ print('Usage: python-rest.py <connection string>')
sys.exit(2)
if len(arguments) == 0:
- print 'Usage: python-rest.py <connection string>'
+ print('Usage: python-rest.py <connection string>')
sys.exit(2)
#set default host for Flask
diff --git a/bindings/python/example_scripts/simple_book.py b/bindings/python/example_scripts/simple_book.py
index bbc3354..4bde608 100644
--- a/bindings/python/example_scripts/simple_book.py
+++ b/bindings/python/example_scripts/simple_book.py
@@ -10,16 +10,16 @@ from gnucash import Session
# We need to tell GnuCash the data format to create the new file as (xml://)
uri = "xml:///tmp/simple_book.gnucash"
-print "uri:", uri
+print("uri:", uri)
ses = Session(uri, is_new=True)
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()
+print("Book is saved:", not book.session_not_saved())
-print "saving..."
+print("saving...")
ses.save()
-print "Book is saved:", not book.session_not_saved()
+print("Book is saved:", not book.session_not_saved())
ses.end()
diff --git a/bindings/python/example_scripts/simple_business_create.py b/bindings/python/example_scripts/simple_business_create.py
index 40a2c3a..75a0022 100644
--- a/bindings/python/example_scripts/simple_business_create.py
+++ b/bindings/python/example_scripts/simple_business_create.py
@@ -62,10 +62,10 @@ from gnucash.gnucash_core_c import \
GNC_OWNER_CUSTOMER, ACCT_TYPE_LIABILITY
if len(argv) < 2:
- print 'not enough parameters'
- print 'usage: simple_business_create.py {new_book_url}'
- print 'example:'
- print "gnucash-env python simple_business_create.py sqlite3:///home/blah/blah.gnucash"
+ print('not enough parameters')
+ print('usage: simple_business_create.py {new_book_url}')
+ print('example:')
+ print("gnucash-env python simple_business_create.py sqlite3:///home/blah/blah.gnucash")
exit()
diff --git a/bindings/python/example_scripts/test_imbalance_transaction.py b/bindings/python/example_scripts/test_imbalance_transaction.py
index f50dea9..d220728 100644
--- a/bindings/python/example_scripts/test_imbalance_transaction.py
+++ b/bindings/python/example_scripts/test_imbalance_transaction.py
@@ -42,10 +42,10 @@ from gnucash import Session, Transaction, Split, Account, GncNumeric, \
# and trading accounts disabled
if len(argv) < 2:
- print 'not enough parameters'
- print 'usage: test_imbalance_transaction.py {book_url}'
- print 'examples:'
- print "gnucash-env python test_imbalance_transaction.py '/home/username/test.gnucash'"
+ print('not enough parameters')
+ print('usage: test_imbalance_transaction.py {book_url}')
+ print('examples:')
+ print("gnucash-env python test_imbalance_transaction.py '/home/username/test.gnucash'")
exit()
@@ -86,12 +86,12 @@ try:
s2.SetAccount(account2)
s2.SetValue(GncNumeric(4))
s2.SetAmount(GncNumeric(4))
- print 'overall imbalance', a.GetImbalanceValue().to_string()
+ print('overall imbalance', a.GetImbalanceValue().to_string())
- print 'per-currency imbalances'
+ print('per-currency imbalances')
imbalance_list = a.GetImbalance()
for (commod, value) in imbalance_list:
- print value.to_string(), commod.get_mnemonic()
+ print(value.to_string(), commod.get_mnemonic())
a.CommitEdit()
diff --git a/gnucash/python/pycons/ishell.py b/gnucash/python/pycons/ishell.py
index aa84467..371f32c 100644
--- a/gnucash/python/pycons/ishell.py
+++ b/gnucash/python/pycons/ishell.py
@@ -125,10 +125,10 @@ class Shell:
def shell(self, cmd,verbose=0,debug=0,header=''):
stat = 0
- if verbose or debug: print header+cmd
+ if verbose or debug: print(header+cmd)
if not debug:
input, output = os.popen4(cmd)
- print output.read()
+ print(output.read())
output.close()
input.close()
diff --git a/gnucash/python/pycons/shell.py b/gnucash/python/pycons/shell.py
index 6569d17..d50043e 100644
--- a/gnucash/python/pycons/shell.py
+++ b/gnucash/python/pycons/shell.py
@@ -153,7 +153,7 @@ class Shell:
console.write (buf, 'output')
if len(buf) < 256: break
# Command output
- print `r`
+ print(`r`)
except SyntaxError:
exec self.command in self.globals
except:
@@ -166,8 +166,8 @@ class Shell:
tb = sys.exc_traceback
if tb:
tb=tb.tb_next
- traceback.print_exception (sys.exc_type, sys.exc_value, tb)
+ traceback.print(_exception (sys.exc_type, sys.exc_value, tb))
except:
sys.stderr, console.stderr = console.stderr, sys.stderr
- traceback.print_exc()
+ traceback.print(_exc())
Summary of changes:
.../python/example_scripts/account_analysis.py | 14 ++---
.../python/example_scripts/gncinvoice_jinja.py | 70 +++++++++++-----------
bindings/python/example_scripts/gncinvoicefkt.py | 6 +-
bindings/python/example_scripts/latex_invoices.py | 70 +++++++++++-----------
.../new_book_with_opening_balances.py | 10 ++--
bindings/python/example_scripts/priceDB_test.py | 4 +-
.../example_scripts/price_database_example.py | 12 ++--
bindings/python/example_scripts/quotes_historic.py | 6 +-
.../example_scripts/rest-api/gnucash_rest.py | 10 ++--
bindings/python/example_scripts/simple_book.py | 8 +--
.../example_scripts/simple_business_create.py | 8 +--
.../example_scripts/test_imbalance_transaction.py | 14 ++---
gnucash/python/pycons/ishell.py | 4 +-
gnucash/python/pycons/shell.py | 6 +-
14 files changed, 121 insertions(+), 121 deletions(-)
More information about the gnucash-changes
mailing list