· 8 years ago · Apr 13, 2018, 08:56 AM
1#!/usr/bin/python
2
3import sqlite3
4import subprocess
5
6dbConn = None
7
8#create table Reading
9def create_table_reading():
10 dbConn.execute('''CREATE TABLE IF NOT EXISTS MYTABLE
11 (PID INT NOT NULL,
12 CMD TEXT NOT NULL);''')
13 print "Created";
14
15#Insert sensor reading
16def insert_sensor_reading():
17 for i in range(0,l):
18 query = "INSERT INTO MYTABLE (PID,CMD)
19 VALUES (" + pidstr[i] + ","+ cmdstr[i] +");"
20 i = i + 1
21 dbConn.execute(query)
22 dbConn.commit()
23 print "inserted";
24
25#read from table
26def select_sensor_reading():
27 query = "SELECT * FROM MYTABLE;"
28 cursor = dbConn.execute(query)
29 for row in cursor:
30 print "PID = ", row[0],"n"
31 print "read";
32
33#read from shell
34def read_from_shell():
35 pid = subprocess.check_output("ps -a | awk '{print $1}'", shell =True)
36 cmd = subprocess.check_output("ps -a | awk '{print $4}'", shell =True)
37
38 pidstr = pid.splitlines( )
39 cmdstr = cmd.splitlines()
40 global pidstr,cmdstr,l
41 pidstr = pidstr[1:]
42 cmdstr = cmdstr[1:]
43 l=len(pidstr)
44
45
46#Main
47if __name__ == '__main__':
48
49 dbConn = sqlite3.connect('test.db')
50 print "Opened database successfully";
51 read_from_shell()
52 create_table_reading()
53 insert_sensor_reading()
54 select_sensor_reading()