简体   繁体   English

如何在终端的下一行打印由 '\r' 组成的 pexpect 输出?

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

I have the follwoing code snippet from a pexpect script我有来自预期脚本的以下代码片段

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)

However it gives me an output as follows:但是它给了我如下输出:

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 '

I want the terminal to show proper readable format of the output with line breaks coming in next line as a normal ping operation would do.我希望终端显示输出的正确可读格式,并像正常的 ping 操作一样在下一行换行。 How to do that?怎么做?

You need to decode your binary string.您需要解码二进制字符串。

The encoding to be used may need to be adapted, based on the content of your binary string, but since there are no special characters, I did go with ansi .要使用的编码可能需要根据二进制字符串的内容进行调整,但由于没有特殊字符,我确实使用了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)

Output:输出:

 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