我正在用 python 2.7.3 为 smartctl 写一个包装器...
我正忙于思考如何在 Linux(具体为 Ubuntu x64)中解析 smartctl
程序的输出
我正在通过子进程运行 smartctl -l selftest/dev/sdx
并将输出抓取到一个变量中
这个变量被分解成一个列表,然后我从输出中删除无用的标题数据和空行。
现在,我得到了一个字符串列表,这太棒了!
数据是表格形式的,我想将其解析为充满列表的 dict()(我认为这是通过阅读文档在 Python 中表示表格数据的正确方法)
这是数据示例:
Num Test_Description Status Remaining LifeTime(hours) LBA_of_first_error
# 1 Short offline Completed without error 00% 44796 -
# 2 Short offline Completed without error 00% 44796 -
# 3 Short offline Completed without error 00% 44796 -
# 4 Short offline Completed without error 00% 44796 -
# 5 Short offline Completed without error 00% 44796 -
# 6 Extended offline Completed without error 00% 44771 -
# 7 Short offline Completed without error 00% 44771 -
# 8 Short offline Completed without error 00% 44741 -
# 9 Short offline Completed without error 00% 1 -
#10 Short offline Self-test routine in progress 70% 44813 -
我可以看到一些尝试解析它的问题,并且对解决方案持开放态度,但我也可能只是做错了;-):
- 状态文本
Self-test routine in progress
流过文本的第一个字符Remaining
- 在
Num
列中,9
之后的数字与#
字符之间没有空格分隔
我在这里可能有点离题,但这是我第一次尝试解析如此古怪的东西。
感谢所有愿意提前阅读这面文字墙的人!!!
到目前为止,这是我的代码,如果有人觉得有必要或觉得它有用:
#testStatus.py
#This module provides an interface for retrieving
#test status and results for ongoing and completed
#drive tests
import subprocess
#this function takes a list of strings and removes
#strings which do not have pertinent information
def cleanOutput(data):
cleanedOutput = []
del data[0:3] #This deletes records 0-3 (lines 1-4) from the list
for item in data:
if item == '': #This removes blank items from remaining list
pass
else:
cleanedOutput.append(item)
return cleanedOutput
def resultsOutput(data):
headerLines = []
resultsLines = []
resultsTable = {}
for line in data:
if "START OF READ" in line or "log structure revision" in line:
headerLines.append(line)
else:
resultsLines.append(line)
nameLine = resultsLines[0].split()
print nameLine
def getStatus(sdxPath):
try:
output = subprocess.check_output(["smartctl", "-l", "selftest", sdxPath])
except subprocess.CalledProcessError:
print ("smartctl command failed...")
except Exception as e:
print (e)
splitOutput = output.split('\n')
cleanedOutput = cleanOutput(splitOutput)
resultsOutput(cleanedOutput)
#For Testing
getStatus("/dev/sdb")
最佳答案
它的值(value)(这是一个老问题):smartctl
有一个 --json
标志,您可以使用它然后像普通 JSON 一样解析输出,因为版本7.0
关于Python - 如何解析 smartctl 程序输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22049136/