gpt4 book ai didi

python - 如何在Python中使用正则表达式分割/etc/network/interfaces

转载 作者:行者123 更新时间:2023-11-30 23:02:43 25 4
gpt4 key购买 nike

我正在尝试将 Ubuntu 上的 /etc/network/interfaces 文件格式分解为各个节(正如手册页所称的那样)。

这是我测试脚本的示例接口(interface)文件:

# The loopback network interface
auto lo
iface lo inet loopback

auto eth0
iface eth0 inet static
address 192.168.2.7
netmask 255.255.255.0
network 192.168.2.0
broadcast 192.168.2.255
gateway 192.0.2.254
dns-nameservers 12.34.56.78 12.34.56.79

auto eth0:0
allow-hotplug eth0:0
iface eth0:0 inet static
address 192.168.1.43
netmask 255.255.255.0

auto eth1
iface eth1 inet dhcp

auto eth2
iface eth2 inet6 static
address 2001:db8::c0ca:1eaf
netmask 64
gateway 2001:db8::1ead:ed:beef

auto br0
iface br0 inet static
address 10.10.0.15
netmask 255.255.255.0
gateway 10.10.0.1
bridge_ports eth0 eth1
up /usr/sbin/brctl stp br0 on

我需要的是保存每个节的字符串数组(ifacemappingautoallow-\w+source(-\w+)? 和注释)及其后面的所有文本,直到下一节开始。

我已经尝试过这样的代码,听起来应该可以工作,但它捕获了一个字符串中的所有节:

re.split(r'^(iface|mapping|auto|allow-\w+|source(-\w)?|#.*)[.\n]+?',
open('/etc/network/interfaces').read(), flags=re.MULTILINE)

如何更正正则表达式来实现此目的?

Python版本是2.7

最佳答案

您不需要正则表达式:

def stanza(fle):
with open(fle) as f:
vals = ("iface", "mapping", "auto", "allow-", "source")
tmp = []
for line in f:
if line.startswith(vals):
yield tmp
tmp = [line]
else:
tmp.append(line)
if tmp:
yield tmp


from pprint import pprint as pp
pp(list(stanza("foo.txt")))

输出:

[['# The loopback network interface\n'],
['auto lo\n'],
['iface lo inet loopback\n', '\n'],
['auto eth0\n'],
['iface eth0 inet static\n',
' address 192.168.2.7\n',
' netmask 255.255.255.0\n',
' network 192.168.2.0\n',
' broadcast 192.168.2.255\n',
' gateway 192.0.2.254\n',
' dns-nameservers 12.34.56.78 12.34.56.79\n',
'\n'],
['auto eth0:0\n'],
['allow-hotplug eth0:0\n'],
['iface eth0:0 inet static\n',
' address 192.168.1.43\n',
' netmask 255.255.255.0\n',
'\n'],
['auto eth1\n'],
['iface eth1 inet dhcp\n', '\n'],
['auto eth2\n'],
['iface eth2 inet6 static\n',
' address 2001:db8::c0ca:1eaf\n',
' netmask 64\n',
' gateway 2001:db8::1ead:ed:beef\n',
'\n'],
['auto br0\n'],
['iface br0 inet static\n',
' address 10.10.0.15\n',
' netmask 255.255.255.0\n',
' gateway 10.10.0.1\n',
' bridge_ports eth0 eth1\n',
' up /usr/sbin/brctl stp br0 on']]

如果您想删除空格,请使用 line.strip() 将其删除。

关于python - 如何在Python中使用正则表达式分割/etc/network/interfaces,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34380633/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com