【发布时间】:2018-04-13 22:28:39
【问题描述】:
我正在通过在 DB 中添加 ps -a 的值来探索 python 中的 sqlite3。但是,我没有这样的专栏:来自我的insert_sensor_reading() 功能的 sudo 错误。
我已经标记了整个代码,以防万一有人想交叉验证
#!/usr/bin/python
import sqlite3
import subprocess
dbConn = None
#create table Reading
def create_table_reading():
dbConn.execute('''CREATE TABLE IF NOT EXISTS MYTABLE
(PID INT NOT NULL,
CMD TEXT NOT NULL);''')
print "Created";
#Insert sensor reading
def insert_sensor_reading():
for i in range(0,l):
query = "INSERT INTO MYTABLE (PID,CMD) \
VALUES (" + pidstr[i] + ","+ cmdstr[i] +");"
i = i + 1
dbConn.execute(query)
dbConn.commit()
print "inserted";
#read from table
def select_sensor_reading():
query = "SELECT * FROM MYTABLE;"
cursor = dbConn.execute(query)
for row in cursor:
print "PID = ", row[0],"\n"
print "read";
#read from shell
def read_from_shell():
pid = subprocess.check_output("ps -a | awk '{print $1}'", shell =True)
cmd = subprocess.check_output("ps -a | awk '{print $4}'", shell =True)
pidstr = pid.splitlines( )
cmdstr = cmd.splitlines()
global pidstr,cmdstr,l
pidstr = pidstr[1:]
cmdstr = cmdstr[1:]
l=len(pidstr)
#Main
if __name__ == '__main__':
dbConn = sqlite3.connect('test.db')
print "Opened database successfully";
read_from_shell()
create_table_reading()
insert_sensor_reading()
select_sensor_reading()
编辑:
下面是ps -a 的输出,我将所有 PID 值存储在 pidstr 中,并将所有命令存储在 cmdstr 中。该错误可能是因为在 cmdstr 中存储 sudo 时出现了一些错误,但我不确定为什么会发生。
PID TTY TIME CMD
13280 pts/18 00:00:00 sudo
13281 pts/18 00:00:00 su
13282 pts/18 00:00:00 bash
17482 pts/17 00:00:00 ssh
19635 pts/19 00:00:00 ssh
24531 pts/1 00:00:00 sudo
24538 pts/1 00:00:00 su
24539 pts/1 00:00:00 bash
【问题讨论】:
-
在 insert_sensor_reading() 中使用时,pidstr 和 cmdstr 的内容到底是什么?
-
我正在运行 ps -a 命令,pidstr 是所有正在运行的进程的 PID 列表,cmdstr 是所有命令
-
是的,老实说,我对实际输出很感兴趣。未知列 sudo 很可能来自 cmdstr。但我想我想通了。
-
如果进程列表在您的
ps -a | awk调用之间发生变化会发生什么?然后一切都不同步了。您是否有理由不只解析ps -a的输出? -
@AbhayNayak 正如您在其他语言中所做的那样,以及您将在任何教程中学习的那样:通过让函数产生一个值返回它并让函数使用或使用一个值通过 a参数。