def open_book(self, gnufile): ''' This uses the GnuCash XLM file as a data store. If you are experimenting with DB storage you will have to edit this section to suit. Note that GnuCash recommends using the XML file storage for production use as the database storage is still in development and should only be used for testing. try: self.session = gnucash.Session("pay-test.gnucash", True, False, False) except gnucash.GnuCashBackendException as (errno): print "{0}".format(errno) print "Stopping. Is Gnucash running? Make sure GnuCash is not running \ and that if you are using an XML file storage make sure that a \ lock file doesn't exist in the gnucash file directory." quit(1) ''' self.session = gnucash.Session(gnufile, True, False, False) self.book = self.session.book self.root = self.book.get_root_account() self.comm_table = self.book.get_table() #CURRENCY = {'GBP':'gbp'} self.currency = self.comm_table.lookup("CURRENCY", "GBP") self.acc_bank = self.root.lookup_by_name('Business Account') #print self.acc_bank.GetName() self.acc_exp_salaries = self.root.lookup_by_full_name("Expenses.Salaries") self.acct_liab_NI = self.root.lookup_by_full_name("Liabilities.NI") self.acct_liab_PAYE = self.root.lookup_by_full_name("Liabilities.PAYE") self.acct_liab_student_loan = self.root.lookup_by_full_name("Liabilities.Student Loan") #print self.acc_bank.GetName() return
def open(self): ''' This uses the GnuCash XLM file as a data store. If you are experimenting with DB storage you will have to edit this section to suit. Note that GnuCash recommends using the XML file storage for production use as the database storage is still in development and should only be used for testing. ''' try: self.session = gnucash.Session("xml://%s" % self.gnufile, False, True) except gnucash.GnuCashBackendException as (errno): print "{0}".format(errno) print "Stopping. Is Gnucash running? Make sure GnuCash is not running \ and that if you are using an XML file storage make sure that a \ lock file doesn't exist in the gnucash file directory." quit(1) self.root = self.session.book.get_root_account() self.book = self.session.book self.comm_table = self.book.get_table() self.currency = self.comm_table.lookup("CURRENCY", CURRENCY) self.exp_account = self.root.lookup_by_full_name(EXPENSE_ACCOUNT) self.payable = self.root.lookup_by_full_name(PAYABLE_ACCOUNT) self.xfer_account = self.root.lookup_by_full_name(XFER_ACCOUNT) assert (self.xfer_account != None) assert (self.exp_account != None) assert (self.payable != None)
def main(): args = parse_args() print('Opening GnuCash file...') with gnucash.Session(args.gnucash_path, gnucash.SessionOpenMode.SESSION_NORMAL_OPEN) as sess: gnc_converter = converter.Converter(sess.get_book()) print('Start conversion...') entries = gnc_converter.convert(currency=args.currency) with open(args.beancount_path, 'w') as outfile: printer.print_entries(entries, file=outfile) print('Done!')
session.destroy() try: options, arguments = getopt.getopt(sys.argv[1:], 'h:', ['host=']) except getopt.GetoptError as err: print str(err) # will print something like "option -a not recognized" print 'Usage: python-rest.py <connection string>' sys.exit(2) if len(arguments) != 1: print 'Usage: python-rest.py <connection string>' sys.exit(2) #set default host for flash host = '127.0.0.1' #allow host option to be changed for option, value in options: if option in ("-h", "--host"): host = value #start gnucash session base on connection string argument session = gnucash.Session(arguments[0], ignore_lock=True) # register method to close gnucash connection gracefully atexit.register(shutdown) # start Flask server app.run(host=host)
if __name__ == '__main__': # Set up: logging.basicConfig(level=logging.INFO) if len(sys.argv) != 3: logging.fatal('Wrong arguments. Usage: ./script.py [input_moneyguru_file] [output_gnucash_file]') sys.exit(1) # - source file root = ET.parse(sys.argv[1]).getroot() if root.tag != 'moneyguru-file': logging.fatal('Urecognized file format') sys.exit(1) # - destination file session = gnucash.Session(sys.argv[2], is_new=True) DEFAULT_CCY = session.book.get_table().lookup("CURRENCY", "EUR") # The parsing itself for child in root: if child.tag == 'group': # Groups groupName = unidecode(unicode(child.attrib['name'])) groupType = child.attrib['type'] acc = gnucash.Account(session.book) acc.SetName(groupName) acc.SetType(moneyGuruToGnuCashAccountType[groupType]) acc.SetCommodity(DEFAULT_CCY) session.book.get_root_account().append_child(acc)
def main(argv=None): if argv is None: argv = sys.argv try: prog_name = argv[0] with_ipshell = False ignore_lock = False no_latex_output = True list_invoices = False output_file_name = "data.lco" invoice_number = None try: opts, args = getopt.getopt(argv[1:], "fhiln:po:", ["help"]) except getopt.error as msg: raise Usage(msg) for opt in opts: if opt[0] in ["-f"]: print("ignoring lock") ignore_lock = True if opt[0] in ["-h", "--help"]: raise Usage("Help:") if opt[0] in ["-i"]: print("Using ipshell") with_ipshell = True if opt[0] in ["-l"]: print("listing all invoices") list_invoices = True if opt[0] in ["-n"]: invoice_number = int(opt[1]) 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) if len(args) > 1: print("opts:", opts, "args:", args) raise Usage("Only one input can be accepted !") if len(args) == 0: raise Usage("No input given !") input_url = args[0] except Usage as err: if err.msg == "Help:": retcode = 0 else: print("Error:", err.msg, file=sys.stderr) print("for help use --help", file=sys.stderr) 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") return retcode # Try to open the given input try: session = gnucash.Session(input_url, ignore_lock=ignore_lock) except Exception as exception: print("Problem opening input.") print(exception) return 2 book = session.book root_account = book.get_root_account() comm_table = book.get_table() EUR = comm_table.lookup("CURRENCY", "EUR") invoice_list = get_all_invoices(book) if list_invoices: for number, invoice in enumerate(invoice_list): print(str(number) + ")") print(invoice) if not (no_latex_output): if invoice_number == None: print("Using the first invoice:") invoice_number = 0 invoice = invoice_list[invoice_number] print("Using the following invoice:") print(invoice) lco_str = invoice_to_lco(invoice) # Opening output file f = open(output_file_name, "w") lco_str = lco_str.encode("latin1") f.write(lco_str) f.close() if with_ipshell: app = TerminalIPythonApp.instance() app.initialize(argv=[]) # argv=[] instructs IPython to ignore sys.argv app.start() #session.save() session.end()
def new_transaction(request, key): accounts = misc_functions.get_accounts_by_webapp_key(key) if len(accounts) != 1: raise ValueError('Can only create transactions for 1 account at a time.') src_account = accounts[0] choices = forms.AccountChoices(accounts) new_tx_form = forms.NewTransactionForm(choices, request.POST) if not new_tx_form.is_valid(): raise ValueError(new_tx_form.errors) txinfo = new_tx_form.cleaned_data txinfo['amount'] = Decimal(txinfo['amount']) global set_home_for_gnucash_api if not set_home_for_gnucash_api: # Bad gnucash depends on $HOME (this dir needs to be writable by the webserver) os.environ['HOME'] = os.path.abspath(os.path.join( os.path.dirname(os.path.dirname(__file__)), 'gnucash_api_home')) set_home_for_gnucash_api = True import gnucash from gnucash_scripts import common # make sure we can begin a session Lock.check_can_obtain() # begin GnuCash API session session = gnucash.Session(settings.GNUCASH_CONN_STRING) try: book = session.book USD = book.get_table().lookup('ISO4217', 'USD') root = book.get_root_account() imbalance = common.get_account_by_path(root, 'Imbalance-USD') acct = common.get_account_by_guid(root, src_account.guid) opposing_acct = common.get_account_by_guid(root, txinfo['opposing_account']) gnc_amount = common.decimal_to_gnc_numeric(Decimal(txinfo['amount'])) # From example script 'test_imbalance_transaction.py' trans = gnucash.Transaction(book) trans.BeginEdit() trans.SetCurrency(USD) trans.SetDescription(str(txinfo['tx_desc'])) trans.SetDate( txinfo['post_date'].day, txinfo['post_date'].month, txinfo['post_date'].year) split1 = gnucash.Split(book) split1.SetParent(trans) split1.SetAccount(acct) if txinfo.has_key('memo'): split1.SetMemo(str(txinfo['memo'])) # The docs say both of these are needed: # http://svn.gnucash.org/docs/HEAD/group__Transaction.html split1.SetValue(gnc_amount) split1.SetAmount(gnc_amount) split1.SetReconcile('c') if opposing_acct != None: split2 = gnucash.Split(book) split2.SetParent(trans) split2.SetAccount(opposing_acct) split2.SetValue(gnc_amount.neg()) split2.SetAmount(gnc_amount.neg()) split2.SetReconcile('c') trans.CommitEdit() finally: session.end() session.destroy() dest_url = request.META.get('HTTP_REFERER') if not dest_url: dest_url = reverse('money_views.views.account', kwargs={'key': key}) return redirect(dest_url)
def open_session_rw(file): mode = gnucash.SessionOpenMode.SESSION_NORMAL_OPEN session = gnucash.Session(file, mode) return session
def open_session(file): mode = gnucash.SessionOpenMode.SESSION_READ_ONLY session = gnucash.Session(file, mode) return session
def main(argv=None): if argv is None: argv = sys.argv try: # default values prog_name = argv[0] ignore_lock = True filename_template = None filename_output = None no_output = False list_invoices = False invoice_number = None invoice_id = None filename_from_invoice = False output_path = None with_ipshell = False try: opts, args = getopt.getopt(argv[1:], "fhliI:t:o:OP:", ["help"]) except getopt.error as msg: raise Usage(msg) for opt in opts: if opt[0] in ["-f"]: 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) + "'.") if opt[0] in ["-i"]: print("Using ipshell") with_ipshell = True if opt[0] in ["-o"]: filename_output = opt[1] print("using output file", filename_output) if opt[0] in ["-O"]: if filename_output: print("given output filename will be overwritten,") print("creating output filename from Invoice data.") filename_from_invoice = True if opt[0] in ["-t"]: filename_template = opt[1] print("using template file", filename_template) if opt[0] in ["-l"]: list_invoices = True print("listing invoices") if opt[0] in ["-P"]: output_path = opt[1] print("output path is", output_path + ".") # Check for correct input if len(args) > 1: print("opts:", opts, "args:", args) raise Usage("Only one input possible !") if len(args) == 0: raise Usage("No input given !") input_url = args[0] # Check for correct template if not filename_template: no_output = True if not list_invoices: raise Usage("No template given !") # Check for output file if not (filename_output or filename_from_invoice): if filename_template: filename_output = filename_template + ".out" print("no output filename given, will be:", filename_output) except Usage as err: if err.msg == "Help:": retcode = 0 else: print("Error:", err.msg, file=sys.stderr) print("for help use --help", file=sys.stderr) 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 (read only)") 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( "-O create output filename by date, owner and invoice number" ) print( "-P path path for output file. Overwrites path in -o option" ) return retcode # Try to open the given input try: print("Opening", input_url, " (ignore-lock = read-only)." if ignore_lock else ".") session = gnucash.Session( input_url, SessionOpenMode.SESSION_READ_ONLY if ignore_lock else SessionOpenMode.SESSION_NORMAL_OPEN, ) except Exception as exception: print("Problem opening input.") print(exception) return 2 book = session.book root_account = book.get_root_account() comm_table = book.get_table() EUR = comm_table.lookup("CURRENCY", "EUR") invoice_list = get_all_invoices(book) if list_invoices: for number, invoice in enumerate(invoice_list): print(str(number) + ")") print(invoice) if not (no_output): if invoice_id: invoice = book.InvoiceLookupByID(invoice_id) if not invoice: print("ID not found.") return 2 if invoice_number: invoice = invoice_list[invoice_number] print("Using the following invoice:") print(invoice) path_template = os.path.dirname(filename_template) filename_template_basename = os.path.basename(filename_template) loader = jinja2.FileSystemLoader(path_template) env = jinja2.Environment(loader=loader) template = env.get_template(filename_template_basename) # company = gnucash_business.Company(book.instance) output = template.render(invoice=invoice, locale=locale) # , company=company) if filename_from_invoice: filename_date = invoice.GetDatePosted().strftime( "%Y-%m-%d") # something like 2014-11-01 filename_owner_name = str(invoice.GetOwner().GetName()) filename_invoice_id = str(invoice.GetID()) filename_output = (filename_date + "_" + filename_owner_name + "_" + filename_invoice_id + ".tex") if output_path: filename_output = os.path.join(output_path, os.path.basename(filename_output)) print("Writing output", filename_output, ".") with open(filename_output, "w") as f: f.write(output) if with_ipshell: import IPython IPython.embed()
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 # Try to open the given input try: session = gnucash.Session(input_url, ignore_lock=ignore_lock) except Exception as exception: print "Problem opening input." print exception return 2 book = session.book root_account = book.get_root_account() comm_table = book.get_table() EUR = comm_table.lookup("CURRENCY", "EUR") invoice_list = get_all_invoices(book) if list_invoices: for number, invoice in enumerate(invoice_list): print str(number) + ")"
handler = logging.handlers.SysLogHandler("/dev/log") handler.setLevel(level=logging.DEBUG) handler.setFormatter( logging.Formatter('gnucash-check-prices: %(levelname)s %(message)s')) root.addHandler(handler) ok = True logging.debug("Start") start = datetime.today() while datetime.today() - start < timedelta(hours=1): try: before = datetime.today() session = gnucash.Session(args.file, is_new=False) after = datetime.today() logging.debug(f"File load time: {after - before}") except gnucash.gnucash_core.GnuCashBackendException as e: if gnucash.ERR_BACKEND_LOCKED not in e.errors: raise logging.debug("Backend locked") time.sleep(60) continue try: (commodities, currencies, prices) = read_prices(session) if args.remove_user_currency: remove_user_currency_prices(session, currencies) if args.remove_user_commodity: remove_user_commodity_prices(session, currencies)
parser = argparse.ArgumentParser( description='Produce expense report from GnuCash database.') parser.add_argument('input', help='GnuCash database file or SQL path.') parser.add_argument('--accounts', nargs='+', default=['Assets', 'Bank', 'Liabilities'], help='Accounts to use for finding transactions.') parser.add_argument('--output', help='Output PDF file name.') args = parser.parse_args() # GnuCash uses '.' in the full name lookup for some reason args.accounts = [name.replace(':', '.') for name in args.accounts] data = [] print('Reading data from "%s" ...' % (args.input, )) sess = gnucash.Session(args.input, is_new=False) try: root = sess.book.get_root_account() for name in args.accounts: acc = root for sub in name.split('.'): acc = acc.lookup_by_name(sub) acc_data = read_account_transactions(acc) data.extend(acc_data) finally: sess.end() rates = {}
def open_gnucash_file(gnucashfile): """Open the given GNUCash file (after making it's backup in the same dir) and return gnucash.Session object""" create_backup(gnucashfile) return gnucash.Session(gnucashfile)
numerator_place_value *= TEN if decimal_value.is_signed(): numerator = -numerator if exponent < 0: denominator = TEN**(-exponent) else: numerator *= TEN**exponent denominator = 1 return GncNumeric(numerator, denominator) # Very basic try for database opening. #NB: DO NOT USE YOUR REAL DATA FILE! This script will write the new invoice # into the named file, you probably do not want this to happen to your real data!! try: session = gnucash.Session("xml://%s" % FILE, False, False, False) except gnucash.GnuCashBackendException, backend_exception: errno = backend_exception.errors[0] ## get first error number print backend_exception # Do something with it print backend_errors.error_dic[errno] # print "Cannot create session. A lockfile may exist or you have GnuCash open." resp = raw_input("Enter y to open anyway: ") if not resp == 'y': print "Quitting on user response. Database was not changed." quit() else: try: session = Session("xml://%s" % FILE, False, True) except GnuCashBackendException as (errno): print "{0}".format(errno)
p_number) + ".csv" # output filename for csv # Check if CSV file already exists. If it does, assume we've run this before and quit if not os.path.exists(csv_filename): csv_file = open(csv_filename, "w") else: # Crude check if we've run this before. TODO: Could be improved print "%sYou appear to have already run this for this period.%s \ I will quit now to give you time to think about what you are doing.%s" % ( LE, LE, LE) quit() csv_line = "date,task,duration,rate" + LE csv_file.write(csv_line) # For direct to gnucash session = gnucash.Session( "xml://%s" % FILE, IGNORE_LOCK, False, False) ## DANGEROUS if IGNORE LOCK = True TESTING ONLY!!!! assert (session != None) root = session.book.get_root_account() assert (root != None) book = session.book income = root.lookup_by_name("Earned Income") assert (income != None) if income.GetType() == -1: print "Didn't get income account exiting" session.end() quit() assets = root.lookup_by_name("Assets") recievables = assets.lookup_by_name("Accounts Recievable") comm_table = book.get_table() gbp = comm_table.lookup("CURRENCY", "GBP")