尝试regex python3子进程命令输出时出错
我的头一直撞在墙上 我想在python脚本中运行一个特定的cli命令,然后在它的输出中运行regex。但我得到了以下错误:尝试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
"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
返回任何内容,这会导致解包失败。