我正在一个接受 .log 文件 POSTS(基本上只是一个文本文件)的烧瓶服务器上工作。这些文件包含调用命令行 smartctl 命令产生的数据
smartctl -a /dev/sda
我让它工作了,但我使用了硬编码文件中的行号,这不是最佳的,因为行数可能因不同的硬盘而异。以下是我的工作代码的一部分:
def parse_line(line): # For colons; device info
splitted = line.split(':')
return splitted[0], splitted[1].strip()
file_body = request.form['smartdata']
lines = file_body.split("\n")
my_data = {} # Empty dictionary object
for line in lines[4:22]: # Device info
if ":" in line:
if line.startswith("Device is:"): # Not necessary
pass
else:
key, value = parse_line(line)
my_data[key] = value
我尝试在 .log 文件中搜索部分标题,以确定我应该做什么样的拆分;
def parse_line(line): # For colons; device info
splitted = line.split(':')
return splitted[0], splitted[1].strip()
copy = False
device_info = {}
for line in lines:
if line.strip() == "=== START OF INFORMATION SECTION ===": #start of device info
copy = True
if line.strip() == "=== START OF READ SMART DATA SECTION ===": #start of smart data section, end of device info
copy = False
if copy: #if iterating lines and passed the information section header, true and sends said line to the parse_line method
key, value = parse_line(line)
device_info[key] = value
但是,我收到以下错误:
UnboundLocalError:赋值前引用了局部变量“值”
我不太明白如何从
device_info[key] = value
因为我基本上和以前一样在做同样的事情。
该device_info[key] = value
行不应该在value
分配 get 的同一块中吗?
def parse_line(line): # For colons; device info
splitted = line.split(':')
return splitted[0], splitted[1].strip()
copy = False
device_info = {}
for line in lines:
if line.strip() == "=== START OF INFORMATION SECTION ===": #start of device info
copy = True
if line.strip() == "=== START OF READ SMART DATA SECTION ===": #start of smart data section, end of device info
copy = False
if copy: #if iterating lines and passed the information section header, true and sends said line to the parse_line method
key, value = parse_line(line)
# Now value will always be defined.
device_info[key] = value
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句