· 7 years ago · Mar 04, 2019, 04:32 PM
1import sqlite3
2import datetime
3from time import sleep
4import sys
5
6# without args - logging
7# args is print - print log
8# args is clear - clear log
9
10dbpath = 'log.db'
11
12def currtime():
13 return str(f"{datetime.datetime.now():%d.%m.%y-%H:%M:%S}")
14
15def init(data):
16 c = sqlite3.connect(dbpath)
17 myCursor = c.cursor()
18 myCursor.executescript(
19 '''CREATE TABLE IF NOT EXISTS conditions (id INTEGER PRIMARY KEY autoincrement, start ,stop);''')
20 myCursor.execute("INSERT INTO conditions (start,stop) VALUES (?, ?);", [data,data])
21
22 # return new record id
23 myCursor.execute("SELECT * FROM conditions ORDER BY id DESC LIMIT 1")
24 result = myCursor.fetchone()
25
26 c.commit()
27 c.close()
28 return result[0]
29
30def push(rec_id,data):
31 c = sqlite3.connect(dbpath)
32 myCursor = c.cursor()
33 myCursor.execute("UPDATE conditions SET stop = ? WHERE id = ?;", [data,rec_id])
34 c.commit()
35 c.close()
36
37def print_recods():
38 c = sqlite3.connect(dbpath)
39 myCursor = c.cursor()
40 myCursor.execute("SELECT * FROM conditions")
41 while True:
42 row = myCursor.fetchone()
43 if row == None:
44 break
45 print(str(row[0]) + ' ' + str(row[1]) + ' --> ' + str(row[2]))
46
47def del_recods():
48 c = sqlite3.connect(dbpath)
49 myCursor = c.cursor()
50 myCursor.execute("DELETE FROM conditions")
51 c.commit()
52 c.close()
53 print('delete complete')
54
55if len(sys.argv)> 1:
56 if sys.argv[1] == 'print':
57 try:
58 print_recods()
59 except Exception as e:
60 print('Error is ', e)
61
62 exit(0)
63
64if len(sys.argv)> 1:
65 if sys.argv[1] == 'clear':
66 try:
67 del_recods()
68 except Exception as e:
69 print('Error is ', e)
70 exit(0)
71
72else:
73 rec_id = init(currtime())
74 while True:
75 sleep(1)
76 push(rec_id, currtime())