寻求更高效解析subprocess stdout的Python实现方案
更高效解析NordVPN连接结果的实现方式
你的原代码通过多次字符串替换、分割提取目标内容,步骤偏繁琐。其实可以直接用正则表达式精准匹配目标字符串,一步到位,效率更高,逻辑也更清晰。
优化后的代码
#!/usr/bin/python3.9 import re result = """- - - New feature - Meshnet! Link remote devices in Meshnet to connect to them directly over encrypted private tunnels, and route your traffic through another device. Use the `nordvpn meshnet --help` command to get started. Learn more: https://nordvpn.com/features/meshnet/-\\|/-\\|/-\\| Connecting to Australia #685 (au685.nordvpn.com)-\\|/-\\ You are connected to Australia #685 (au685.nordvpn.com)!-""" # 直接匹配目标模式,提取到结尾的括号为止 match = re.search(r'You are connected to .+?\)', result) if match: target_result = match.group() print(target_result)
优化说明
- 精准匹配:目标内容有固定格式,用
re.search直接定位包含"You are connected to"且以")"结尾的片段,一次匹配就能拿到结果,省去多次字符串替换和分割的开销。 - 避免冗余操作:原代码里的多次替换、去空格、删除无关内容等步骤都可以省略,正则匹配直接跳过无关信息,只提取需要的部分。
- 解决分割失败问题:你之前尝试用"-|/-"分割失败,是因为原字符串里的分隔符是转义后的
-\|/-,直接分割需要处理转义字符反而麻烦,正则匹配完全不需要考虑这些干扰项。
内容的提问来源于stack exchange,提问作者bob_the_bob
相关产品推荐
相关产品推荐

