将 sed 正则表达式从 Shell 转换为 Python 脚本的最佳方法

Best way to transpose sed regex from Shell to Python script

我有一个包含这些行的文件

Entry :  12300000
F Blocks:   0x00000020 0x00000000 0x000a1b00
S Blocks:   0x00100000 0x0000001c 0x00000150

使用 shell 脚本,可以使用以下行提取以 F Blocks: 开头的行的十六进制值:

blocks="$(sed -nE 's/F Blocks:[\t ]+(0x)?([0-9a-f]+)[ ]+(0x)?([0-9a-f]+)[ ]+(0x)?([0-9a-f]+)/0x 0x 0x/p' filename)"

我想在 Python 脚本中执行相同的提取,使用子进程模块

import subprocess
sed_cmd = ['sed', '-n', '-E', "s/F Blocks:[\t ]+(0x)?([0-9a-f]+)[ ]+(0x)?([0-9a-f]+)[ ]+(0x)?([0-9a-f]+)/0x\2 0x\4 0x\6/p", 'filename']
proc = subprocess.Popen(sed_cmd, stdout=subprocess.PIPE)
blocks = proc.stdout.read()

是否有提取数据和变量输出的最佳实践,或者可以简化?

使用普通 Python:

results = []                                # Define a list for matches
with open(filepath,'r') as fr:              # Open the file stream
    for line in fr:                         # Read line by line
        if line.startswith("F Blocks:"):    # If line starts with our value
            results = line[line.find(':')+1:].split() # Get all after : and split with whitespace
            # break                         # Uncomment this if you needn't process the file any longer

print(results)

看到 online demo