![](/img/trans.png)
[英]How to remove \n\r or [] in stdout.readlines() in paramiko python
[英]How can I remove \n and \r\n from stdout in python?
我有這個腳本:
#!/usr/bin/python
import subprocess
import sys
HOST="cacamaca.caca"
COMMAND="display mac-address 0123-4567-8910"
ssh = subprocess.Popen(["ssh", "%s" % HOST, COMMAND],
shell=False,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
result = ssh.stdout.readlines()
if result == []:
error = ssh.stderr.readlines()
print >>sys.stderr, "ERROR: %s" % error
else:
print result
因為輸出包含空格和不同的行,所以它也輸出回車符和新行,因此結果不是干凈的:
['\\ r \\ n','cacamaca.caca \\ r \\ n','信息:在線的VTY用戶的最大數量為10,而當前在線的VTY用戶的數量為'r \\ n','為2。\\ r \\ n','當前登錄時間為DST 2017-07-20 20:10:54 + 03:00。\\ r \\ n','---------------- -------------------------------------------------- ------------- \\ r \\ n','從類型\\ r \\ n學習到的MAC地址VLAN / VSI,'-------------- -------------------------------------------------- --------------- \\ r \\ n','0123-4567-8910 1234 /-Eth-Trunk9動態\\ r \\ n','\\ r \\ n','- -------------------------------------------------- --------------------------- \\ r \\ n','顯示的總項目數= 1 \\ n','\\ r \\ n', ”]
如何刪除'\\ n'和'\\ r \\ n'或至少用空格替換它們,以使結果看起來像原始的? 我確實閱讀了很多有關此問題的答案,但沒有一個幫助。
您的result
變量是一個列表。 我認為您想將結果加入單個字符串並打印出來。 你可以這樣用str.join()
做到這一點
print ''.join(result)
這將導致以下輸出
cacamaca.caca
Info: The max number of VTY users is 10, and the number
of current VTY users on line is 2.
The current login time is 2017-07-20 20:10:54+03:00 DST.
-------------------------------------------------------------------------------
MAC Address VLAN/VSI Learned-From Type
-------------------------------------------------------------------------------
0123-4567-8910 1234/- Eth-Trunk9 dynamic
-------------------------------------------------------------------------------
Total items displayed = 1
您可以使用.strip()
刪除換行符,或使用.replace()
替換它們,例如:
result = [x.strip() for x in result]
輸出:
['', 'cacamaca.caca', 'Info: The max number of VTY users is 10, and the number', 'of current VTY users on line is 2.', 'The current login time is 2017-07-20 20:10:54+03:00 DST.', '-------------------------------------------------------------------------------', 'MAC Address VLAN/VSI Learned-From Type', '-------------------------------------------------------------------------------', '0123-4567-8910 1234/- Eth-Trunk9 dynamic', '', '-------------------------------------------------------------------------------', 'Total items displayed = 1', '', '']
您可以使用以下代碼刪除“ \\ n”和“ \\ r \\ n”。
with subprocess.Popen(["ssh", "%s" % HOST, COMMAND], shell=False) as ssh:
result = ssh.communicate()[0]
print(result)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.