python中的输出与python3不同(相同的脚本)

2024-09-29 11:25:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我用Python2编写代码,一切都很顺利,但是当我在python3中使用相同的代码时,输出不是我想要的那么合适,或者看起来不像Python2,我如何解决这个问题

import paramiko
import time
UserName = "*****"
Password = "******"
ip = "10.226.159.1"

ssh_client = paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh_client.connect(hostname=ip, username=UserName, password=Password)
remote_connection = ssh_client.invoke_shell()
remote_connection.send("show  interfaces transceiver \n")

time.sleep(10)
output = remote_connection.recv(65535)
print (output)

python2中的输出:

 Rp#sh int tra
 If device is externally calibrated, only calibrated values are printed.
 ++ : high alarm, +  : high warning, -  : low warning, -- : low alarm.
 NA or N/A: not applicable, Tx: transmit, Rx: receive.
 mA: milliamperes, dBm: decibels (milliwatts).

              Optical   Optical
       Temperature  Voltage  Tx Power  Rx Power
     Port       (Celsius)    (Volts)  (dBm)     (dBm)
     ---------  -----------  -------  --------  --------
     Te1/1/1      24.3       3.26      -2.9      -1.8
     Te1/1/3      34.7       3.35      -1.1     -13.7
     Te1/1/4      32.6       3.20      -3.5      -1.6

python 3中的输出:

     b'\r\nRp#sh int tra\r\nIf device is externally calibrated, only calibrated values are 
   printed.\r\n++ : high alarm, +  : high warning, -  : low warning, -- : low alarm.\r\nNA or   
   N/A: not applicable, Tx: transmit, Rx: receive.\r\nmA: milliamperes, dBm: decibels 
   (milliwatts).\r\n\r\n                                 Optical   Optical\r\n          Temperature  Voltage  Tx Power  Rx Power\r\nPort       (Celsius)    (Volts)  (dBm)     (dBm)\r
 \n---------  -----------  -------  --------  --------\r\nTe1/1/1      25.2       3.26      -2.9      -1.8   \r\nTe1/1/3      35.5       3.35      -1.1     -13.6   \r\nTe1/1/4      33.6       3.21      -3.5      -1.6   \r\n\r\n\r\n

Tags: clientparamikoremoteconnectionrxsshlowpower
2条回答

要在python 3中正确打印输出,需要将数据类型从bytes更改为string:

>>> print(output.decode())
Rp#sh int tra
If device is externally calibrated, only calibrated values are printed.
++ : high alarm, +  : high warning, -  : low warning,   : low alarm.
NA or   N/A: not applicable, Tx: transmit, Rx: receive.
mA: milliamperes, dBm: decibels (milliwatts).

                                 Optical   Optical
          Temperature  Voltage  Tx Power  Rx Power
Port       (Celsius)    (Volts)  (dBm)     (dBm)
    -       -     -            
Te1/1/1      25.2       3.26      -2.9      -1.8   
Te1/1/3      35.5       3.35      -1.1     -13.6   
Te1/1/4      33.6       3.21      -3.5      -1.6  

b为前缀的字符串是字节文字(请参阅此处What does the 'b' character do in front of a string literal?的更多详细信息)

要打印字节文字,首先需要将其转换为字符串:

# Check if we have string or bytes. Convert to string, if necessary
if type(output) == bytes:
    output = output.decode() 
print(output)

这段代码应该可以在python2和python3中使用

相关问题 更多 >