我有一个由数据组成的文件,我试图从文件中获取特定的输出。当我使用"返回" [使用return进一步隔离输出]循环语句只打印输出的第一行。
我已正确定义了所有变量:
def show_command(filename, startline, endline):
with open(filename) as input_data:
for line in input_data:
if line.strip() == startline:
break
for line in input_data:
if line.strip() == endline:
break
output = line
return output
show_command(filename, startline, endline)
#
它只打印总输出的第一行。
当前引导变量:
###实际输出是当前引导变量:
SUP-1 NXOS变量= bootflash:/nxos.7.0.3.I4.6.bin 没有模块启动变量集
下次重新加载时引导变量:
SUP-1 NXOS变量= bootflash:/nxos.7.0.3.I4.6.bin 没有模块启动变量集
#答案 0 :(得分:0)
嗯,您只返回捕获的行,您需要在返回之前收集所有行,例如:
def show_command(filename, startline, endline):
with open(filename, "r") as input_data:
output = None # hold our contents
for line in input_data:
if line.strip() == startline:
output = "" # start collecting lines
elif line.strip() == endline: # end of our area of interest
break # end the loop
elif output is not None: # if we started collecting lines...
output += line # collect the current line
return output # return the collected lines
或者如果你想用你的方法做到这一点:
def show_command(filename, startline, endline):
with open(filename, "r") as input_data:
for line in input_data:
if line.strip() == startline:
break
output = ""
for line in input_data:
if line.strip() == endline:
break
output += line
return output