将sed正则表达式从Shell转换为Python脚本的最佳方法
我有一个包含这些行的文件将sed正则表达式从Shell转换为Python脚本的最佳方法,python,regex,sed,subprocess,pipe,Python,Regex,Sed,Subprocess,Pipe,我有一个包含这些行的文件 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-9
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\2 0x\4 0x\6/p' filename)"
我想在Python脚本中使用subprocess模块进行同样的提取
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)
请参阅。最好的方法是从头重写代码,例如,将文本中的行替换为
。拆分行():
为,并将打开的(文件路径,'r')替换为fr:for-in-fr:
。这里不需要正则表达式。为什么不使用python
的re
模块,而不是调用sed
?@WiktorStribiżew谢谢!。所有的Shell逻辑都已转移到Python中。需要更多的时间,但效果很好!总之,在Python函数中使用SUBSPROCESS移动use Shell命令只是一种快速而肮脏的方法。