Python 读取并搜索文件中的字符串

Python read and search String in a file

我想编写一个脚本来读取 apache.conf 文件并获取 "MaxClients" 值、"Keepalive" 值、"KeepAliveTimeout" 值和 "ServerLimit" 值等,到不同的论点。但如果该行以“#”值开头,则不应读取它。我已经编写了如下示例代码,但它并没有忽略#value,有人可以帮我做这个吗,我只需要这个值。

import re

#afile = open('apache.txt','r')
#for aline in afile:
#    aline1 = aline.rstrip()
#    ax = re.findall('MaxClients ',aline1 )
#    print(ax)

with open('apache.txt','r') as afile:
    for line in afile:
        match = re.search('MaxClients ([^,]+)', line )
        if match:
            print(match.group(1))

更改 re.search 函数,如下所示。

match = re.search(r'^(?! *#).*MaxClients ([^,]+)', line )

(?! *#) 否定前瞻断言行的开头后面没有 # 符号。