鍍金池/ 問答/Python  HTML/ 如何將subproccess中的stdout的\n替換成<br>

如何將subproccess中的stdout的\n替換成<br>

我想要將subproccess的stout中的n替換成
,我嘗試了如下,都無效,用的是python3

a=subproccess.Popen('ls -al',stdout=subproccess.PIPE,shell=Ture)

我先用了如下代碼,但是有有報錯‘str’does not support the buffer interface

b=a.stdout.read().replace('\n','<br>') 

然后我又試了如下命令,沒有報錯,但是并沒有替換成功

b=str(a.stdout.read()).replace('\n','<br>') 
回答
編輯回答
晚風眠

你這代碼從頭到尾都不對啊。你問問題的時候能把代碼整理好嗎?使用的 python 版本也沒說明

我假設你使用的是 python2,你想從 subprocess 中讀到標準輸出,正確的寫法是:

a = subprocess.Popen('ls -l', shell=True, stdout=subprocess.PIPE)
b = a.stdout.read().replace('\n', '<br>')

如果是 python3,a.stdout.read() 得到的是 bytes,所以可以:

b = a.stdout.read().decode().replace('\n', '<br>')
2018年3月24日 02:11