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

时间:2016-03-11 11:20:08

标签: python regex

我一直在我的头撞在墙上......

我想从python脚本中运行一个特定的cli命令然后正则表达它的输出。但是我收到以下错误:

// create contact
var contact: CNMutableContact = CNMutableContact()
contact.familyName = "Doe"
contact.givenName = "John"

// Add mobile number
var mobileNumber: CNLabeledValue = CNLabeledValue.labeledValueWithLabel(CNLabelPhoneNumberMobile, value: CNPhoneNumber.phoneNumberWithStringValue("123-123-1212"))
contact.phoneNumbers = [mobileNumber]
var request: CNSaveRequest = CNSaveRequest()
request.addContact(contact, toContainerWithIdentifier: nil)

// save contact
NSError * saveError
if !store.executeSaveRequest(request, error: saveError) {
    NSLog("error = %@", saveError)
}

这是我的简短代码:

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

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

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

Regex woes with Subprocess output

提前致谢,

1 个答案:

答案 0 :(得分:1)

在Python3中,Popen.communicate返回bytes,而regex_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 1}}和bytes

更新:正如Duncan在评论中所指出的那样,在"\n"电话中将b"\n"替换为split同样有效。