2016-03-11 28 views
0

我一直在敲打我的頭靠在這裏牆上...錯誤嘗試正則表達式python3子命令輸出

我想從一個python腳本中運行特定的CLI命令,然後正則表達式,它的輸出時。但我得到以下錯誤:

"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) 

這應該是簡單的調試,但我不能找到解決方案。

使用以下的職位,但仍然無法解決:提前

Regex woes with Subprocess output

感謝,

保羅

回答

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,因爲這同時適用於strbytes

更新:由鄧肯注意到在評論,在split通話與b"\n"更換"\n"將工作一樣好。

+0

或者你可以使用'data.split(b'\ n')',因爲問題僅僅是'split'調用中'str'和'bytes'的混合。 – Duncan

+0

正則表達式匹配也會失敗,請嘗試're.compile(「foo」).search(b「foo」)'。 –

+0

是的,我並沒有抱怨你的答案的部分,只是你暗示'.split()'實際上不適用於字節。 (不是說使用'.splitlines()'也是有問題的)。 – Duncan