2016-07-28 35 views
1

這讓我頭痛不已。我的代碼:如何從Python3中的變量/文本文件中刪除b和 n? (TypeError)

import subprocess 
proc = subprocess.Popen("php /var/scripts/data.php", shell=True, stdout=subprocess.PIPE) 
scriptresponse = proc.stdout.read() 
print (scriptresponse) 

輸出:

b'January\n'

我試圖scriptresponse.replace ('\n', '')但失敗:

TypeError: 'str' does not support the buffer interface

如何從scriptresponse刪除b\n因此輸出看起來就像這樣:

January

回答

0

嘗試將universal_newlines=True作爲參數添加到Popen調用中。

正如docs提到:

If universal_newlines is True , the file objects stdin, stdout and stderr are opened as text streams in universal newlines mode, as described above in Frequently Used Arguments, otherwise they are opened as binary streams.

現在你有一個二進制字符串(由b表示)。如果仍然有換行符,請使用字符串上的rstrip()方法刪除尾隨字符。