获取文本文件Python中的特定部分并保存到dict UnboudLocalError



我正在研究一个接受.log文件POST(基本上只是一个文本文件(的烧瓶服务器。这些文件包含调用命令行 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:赋值前引用的局部变量"value">

我不太明白我怎么会从

device_info[key] = value

因为我基本上在做和以前一样的事情。

device_info[key] = value行不应该在分配value的同一个块中吗?

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

正如一些人所说,device_info应该正确缩进。我必须添加一个检查以查看":"是否在行中,然后才为我的字典分配一个值,因为我parse_line方法需要冒号来分隔行。以下代码有效。

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 ===":
copy = True
if line.strip() == "=== START OF READ SMART DATA SECTION ===":
copy = False
if copy and ":" in line: # Make sure : is in line to use parse_line
key, value = parse_line(line)
# Value will be defined
device_info[key] = value

最新更新