我一直在我的头撞在墙上......
我想从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
提前致谢,
保
答案 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
同样有效。