簡體   English   中英

如何在終端的下一行打印由 '\r' 組成的 pexpect 輸出?

[英]How to print output of pexpect consisting '\r' in next line of the terminal?

我有來自預期腳本的以下代碼片段

import pexpect
import time
username=<username>
password=<password>
child = pexpect.spawn('ssh <username>@192.168.1.219',timeout=40)
child.expect(['MyUbuntu','\$','\#'])
child.sendline(<password>)
child.expect(['MyUbuntu','\$','\#'])
time.sleep(2)
child.sendline('execute ping 192.168.1.2')
child.expect(['MyUbuntu','\$','\#'])
k=child.before
k=k.splitline
for line in k:
    print(line)

但是它給了我如下輸出:

b' execute ping 192.168.1.2\r\r\nPING 192.168.1.2: 56 data bytes\r\n64 bytes from 192.168.1.2: icmp_seq=0 ttl=62 time=0.2 ms\r\n64 bytes from 192.168.1.2: icmp_seq=1 ttl=62 time=0.2 ms\r\n64 bytes from 192.168.1.2: icmp_seq=2 ttl=62 time=0.2 ms\r\n64 bytes from 192.168.1.2: icmp_seq=3 ttl=62 time=0.2 ms\r\n64 bytes from 192.168.1.2: icmp_seq=4 ttl=62 time=0.1 ms\r\n\r\n--- 192.168.1.2 ping statistics ---\r\n5 packets transmitted, 5 packets received, 0% packet loss\r\nround-trip min/avg/max = 0.1/0.1/0.2 ms\r\n\r\nMyUbuntu '

我希望終端顯示輸出的正確可讀格式,並像正常的 ping 操作一樣在下一行換行。 怎么做?

您需要解碼二進制字符串。

要使用的編碼可能需要根據二進制字符串的內容進行調整,但由於沒有特殊字符,我確實使用了ansi

b = b' execute ping 192.168.1.2\r\r\nPING 192.168.1.2: 56 data bytes\r\n64 bytes from 192.168.1.2: icmp_seq=0 ttl=62 time=0.2 ms\r\n64 bytes from 192.168.1.2: icmp_seq=1 ttl=62 time=0.2 ms\r\n64 bytes from 192.168.1.2: icmp_seq=2 ttl=62 time=0.2 ms\r\n64 bytes from 192.168.1.2: icmp_seq=3 ttl=62 time=0.2 ms\r\n64 bytes from 192.168.1.2: icmp_seq=4 ttl=62 time=0.1 ms\r\n\r\n--- 192.168.1.2 ping statistics ---\r\n5 packets transmitted, 5 packets received, 0% packet loss\r\nround-trip min/avg/max = 0.1/0.1/0.2 ms\r\n\r\nMyUbuntu '
s = b.decode("ansi")
print(s)

輸出:

 execute ping 192.168.1.2
PING 192.168.1.2: 56 data bytes
64 bytes from 192.168.1.2: icmp_seq=0 ttl=62 time=0.2 ms 
64 bytes from 192.168.1.2: icmp_seq=1 ttl=62 time=0.2 ms 
64 bytes from 192.168.1.2: icmp_seq=2 ttl=62 time=0.2 ms 
64 bytes from 192.168.1.2: icmp_seq=3 ttl=62 time=0.2 ms 
64 bytes from 192.168.1.2: icmp_seq=4 ttl=62 time=0.1 ms 

--- 192.168.1.2 ping statistics ---
5 packets transmitted, 5 packets received, 0% packet loss
round-trip min/avg/max = 0.1/0.1/0.2 ms

MyUbuntu

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM