[英]Python: loop doesn't break
Having problem with breaking the loop. 在中断循环时遇到问题。 I want to break it when it reach the end word. 我想在到达结尾时将其断开。 Hopefully you can help me what's I'm missing on this code. 希望您能帮助我这段代码中缺少的内容。 Thank you. 谢谢。
def y():
with open('test.conf', 'r') as rf:
x = list()
for line in rf:
if 'config system global' in line:
x.append('config system global\n')
while True:
x.append(rf.__next__())
if 'end\n' in line:
break
with open('test.txt', 'w') as wf:
wf.writelines(x)
config system global
set admin-maintainer disable
set admin-scp enable
set admin-server-cert "Fortinet_Firmware"
set admintimeout 15
set anti-replay disable
set fgd-alert-subscription advisory latest-threat
set gui-dynamic-routing enable
set gui-multiple-utm-profiles enable
set gui-replacement-message-groups enable
set gui-sslvpn-personal-bookmarks enable
set gui-sslvpn-realms enable
set gui-wireless-opensecurity enable
set hostname "XXXXXX"
set internal-switch-mode interface
set revision-backup-on-logout enable
set revision-image-auto-backup enable
set strong-crypto enable
set tcp-timewait-timer 120
set timezone 80
set vdom-admin enable
end
config system accprofile
edit "prof_admin"
set admingrp read-write
set authgrp read-write
set endpoint-control-grp read-write
set fwgrp read-write
set loggrp read-write
set mntgrp read-write
set netgrp read-write
set routegrp read-write
set sysgrp read-write
set updategrp read-write
set utmgrp read-write
set vpngrp read-write
set wanoptgrp read-write
set wifi read-write
Try using re module
. 尝试使用re module
。
Ex: 例如:
import re
for line in s.split("\n"):
if re.match('end', line):
break
The problem is the internal while
loop: 问题是内部的while
循环:
while True:
x.append(rf.__next__())
if 'end\n' in line:
break
it's an infinite loop, because line
doesn't change within the loop. 这是一个无限循环,因为line
在循环内不会改变。 It probably ends with StopIteration
exception unless it's catched 除非被捕获,否则它可能以StopIteration
异常结束
The proper code would be: 正确的代码是:
while True:
line = rf.__next__()
if 'end\n' in line:
break
x.append(line)
append before or after the test for end
depending on whether you want to keep the end
in the block. 前或测试后追加end
取决于你是否希望保留end
的块。
and de-indent: 和缩进:
with open('test.txt', 'w') as wf:
wf.writelines(x)
at the same level as the other with
block, or the file will be written at each iteration. 与其他with
块处于同一级别,否则文件将在每次迭代时写入。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.