我正在用Python 2.7.3编写一个smartctl的封装器(wrapper)......
我能看到尝试解析这个文本存在一些问题,我愿意听取解决方案,但我可能也做错了;
提前感谢每一个读完这篇拙劣文章的人!!!
以下是迄今为止我的代码,如果有任何人认为或发现它有用的话:
我正在努力理解如何解析Linux(具体来说是Ubuntu x64)中smartctl程序的输出,这真是一场噩梦。
我通过子进程运行smartctl -l selftest /dev/sdx
并将输出存入变量中。
然后将该变量分割成一个列表,再从输出中删除无用的标题数据和空白行。
现在,我得到了一个字符串列表,非常好!
数据有点类似于表格,我想将其解析为一个包含列表的字典(根据文档阅读,我认为这是在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 -
我能看到尝试解析这个文本存在一些问题,我愿意听取解决方案,但我可能也做错了;
- 状态文本“正在进行自检例程”超过了文本“剩余”的第一个字符
- 在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")