尝试regex python3子进程命令outpu时出错

2024-09-30 18:25:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我的头撞到墙上了。。。在

我想从python脚本中运行一个特定的cli命令,然后对它的输出进行regex。但我得到了以下错误:

"File "speedtestcork.py", line 18, in regex_speedtest
    for line in data.split("\n"):
TypeError: Type str doesn't support the buffer API"

下面是我的简短代码:

^{pr2}$

这应该很容易调试,但我找不到解决方案。在

使用了以下帖子,但仍然无法解析:

Regex woes with Subprocess output

提前谢谢你

保罗


Tags: inpy命令脚本fordatacli错误
1条回答
网友
1楼 · 发布于 2024-09-30 18:25:15

在Python3中,^{}返回bytes,而{}需要{}输入。在

以下是更新版本:

def regex_speedtest(data):
    Down_Regex = re.compile(rb'(Download:).(\d+\.\d+).(Mbit/s)')
    Up_Regex = re.compile(rb'(Upload:).(\d+\.\d+).(Mbit/s)')

    for line in data.splitlines():   
        print(line)

我已经将r前缀改为rb,它将字符串文本转换为字节文本,并将split("\n")调用替换为splitlines,因为这对str和{}都有效。在

更新:正如邓肯在评论中所指出的,在split调用中用"\n"替换b"\n"也同样有效。在

相关问题 更多 >