From 6ebca3ff59397b32ea54bbe28eaac617e86d6979 Mon Sep 17 00:00:00 2001 From: "Brian S. Stephan" Date: Mon, 1 Nov 2010 22:17:10 -0500 Subject: [PATCH] simple utility script to take a newline-separated list of facts and insert to database for Facts.py, supporting the format (if you want to call it that) supported by FactFile.py --- scripts/factfile-to-facts.py | 61 ++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 scripts/factfile-to-facts.py diff --git a/scripts/factfile-to-facts.py b/scripts/factfile-to-facts.py new file mode 100644 index 0000000..3f0ad7c --- /dev/null +++ b/scripts/factfile-to-facts.py @@ -0,0 +1,61 @@ +""" +factfiles-to-facts - insert facts from flat file to database +Copyright (C) 2010 Brian S. Stephan + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . +""" + +import argparse +import getpass +import os +import sqlite3 +import socket +import sys + +if __name__ == '__main__': + parser = argparse.ArgumentParser() + parser.add_argument('-f', '--factfile') + parser.add_argument('-c', '--category') + args = parser.parse_args() + + if args.factfile == None or args.category == None: + print('script needs both -c (category) and -f (filename)') + sys.exit(2) + + # database + dbfile = 'dr.botzo.data' + db = sqlite3.connect(dbfile) + + # open file + if os.path.isfile(args.factfile): + with open(args.factfile, 'r') as file: + lines = file.readlines() + for line in lines: + try: + line = line.rstrip() + print('inserting \'' + line + '\'') + db.execute('''INSERT INTO facts_facts (category, fact, who, userhost) + VALUES (?,?,?,?)''', (args.category, line.decode('utf-8', 'ignore'), getpass.getuser(), getpass.getuser() + '@' + socket.getfqdn())) + except sqlite3.Error as e: + db.rollback() + print("sqlite error: " + str(e)) + sys.exit(2) + + db.commit() + else: + print('filename \'' + whats[0] + '\' doesn\'t exist') + + +# vi:tabstop=4:expandtab:autoindent +# kate: indent-mode python;indent-width 4;replace-tabs on;