2016-11-29 69 views
0

我打電話給一個子進程,並在出現錯誤時返回一個字符串。 代碼示例:退出子程序時向字符串添加字符

當調用過程:

def read_plan_with_break(): 
    comand = " python script.py " 
    proc = subprocess.Popen(comand.split(), shell=False, stdout = subprocess.PIPE, stderr= subprocess.PIPE) 
    if proc.wait() != 0: 
     output, err = proc.communicate() 
     print (err) 
     return "Error in subprocess" 
    return True 

退出子進程時:

def fatal_error(): 
    print("Some message", file=sys.stderr) 
    exit(1) 

我的問題是,stderr輸出爲:b'Some message\r\n' 我可以抹去\r\nstrip但不知道爲什麼在開始時有b,在開始和結束時有'

有誰知道爲什麼會發生這種情況?

編輯: 我試圖err.split()[2:-1]擺脫b',但它切斷的Some message

開始。如果我得到了反對票,請解釋一下,所以我可以改進,並在更好的問題未來

+0

它只是表示它是一個字節串。你不能通過子串刪除'b',它不是字符串的一部分。看到[這裏](http://stackoverflow.com/questions/22824539/what-is-a-python-bytestring) –

+0

err.decode()將幫助你 – TheClonerx

+0

@TheClonerx謝謝你,回答,所以我可以接受它:) – kemis

回答

2

err是一個字節串,你應該首先通過err.decode()來解碼它,這將返回字符串