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

尝试regex python3子进程命令输出时出错,python,regex,Python,Regex,我的头一直撞在墙上 我想在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" 以下是我的简短代码: import time import re import speedte

我的头一直撞在墙上

我想在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"
以下是我的简短代码:

import time
import re
import speedtest_cli
import subprocess



def regex_speedtest(data):
        #output, errors = data.communicate()
        #output1 = str(output)
        Down_Regex = re.compile(r'(Download:).(\d+\.\d+).(Mbit/s)')
        Up_Regex = re.compile(r'(Upload:).(\d+\.\d+).(Mbit/s)')

        for line in data.split("\n"):          # code seems to break at this line.
                print(line)
                #Downmatch = Down_Regex.search(line)
                #Upmatch = Up_Regex.search(line)
        #return (Downmatch.group(2), Upmatch.group(2))



while True:
        now = time.strftime("%H:%M:%S %d %m %Y")
        process = subprocess.Popen(["speedtest-cli", "--server", "2432"], shell=True, stdout=subprocess.PIPE)
        output, errors = process.communicate()
        down, up = regex_speedtest(output)
这应该是简单的调试,但我找不到解决方案

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

提前感谢,

Python3中的Paul

返回
字节
,而
regex\u speedtest
需要
str
输入

以下是更新版本:

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
字节都有效

更新:正如邓肯在评论中指出的那样,在
拆分
调用中将
“\n”
替换为
b“\n”
也同样有效。

在Python3中返回
字节
,而
正则表达式测试
需要
str
输入

以下是更新版本:

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
字节都有效


更新:正如邓肯在评论中指出的那样,在
拆分
调用中将
中的“\n”
替换为
b”\n”
也同样有效。

或者您可以使用
数据.split(b'\n')
因为问题只是在
split
调用中混合了
str
bytes
。正则表达式匹配也会失败,试试
re.compile(“foo”).search(b“foo”)
。是的,我没有抱怨你答案的这一部分,只是你暗示了
.split()
在字节内不起作用,而实际上它起作用。(并不是说使用
.splitlines()
也没有任何问题)。谢谢各位,我在这里的第一篇帖子,对响应时间和知识印象深刻:)解决这一问题突出了另一个问题:回溯(最后一次调用):文件“speedtestcork.py”,第37行,在down,up=regex\u speedtest(输出)中TypeError:“非类型”对象不是ITerablet这可能表示您没有从
regex\u speedtest
返回任何内容,这会导致解包失败。或者您可以使用
data.split(b'\n'))
因为问题只是在
split
调用中混合了
str
bytes
。正则表达式匹配也会失败,试试
re.compile(“foo”).search(b“foo”)
。是的,我没有抱怨你答案的这一部分,只是你暗示了
.split()
在字节内不起作用,而实际上它起作用。(并不是说使用
.splitlines()
也没有任何问题)。谢谢各位,我在这里的第一篇帖子,对响应时间和知识印象深刻:)解决这一问题突出了另一个问题:回溯(最后一次调用):文件“speedtestcork.py”,第37行,在down,up=regex\u speedtest(输出)中TypeError:“非类型”对象不是ITerableth这可能表示您没有从
regex\u speedtest
返回任何内容,这会导致解包失败。