打印功能结果python2是正确的,但是python3是错误的

时间:2019-01-15 06:39:30

标签: python-3.x python-2.7

我的程序使用subprocessoptparse模块读取终端输出并打印。

虽然Python 2(2.7.14+)的结果很好,但在Python 3(3.6.7)中却是一行,我看不懂。

我试图将列表转换为字符串

print(str(ifconfig_result))

我尝试过循环

for result in ifconfig_result :
     print(result)

无济于事。

这是我的代码

import subprocess    
import optparse

  def get_arguments():     
      parser = optparse.OptionParser()
      parser.add_option("-i","--interface",dest="interface",help="interface to change its MAC address")
      parser.add_option("-m","--mac",dest="new_mac",help="new MAC address")
      (options,arguments) = parser.parse_args() 
      if not options.interface:
             parser.error("[-] Plase specify an interface, use --help for more info.")
      elif not options.new_mac:
           parser.error("[-] Plase specify a mac, use --help for more info.")
      return options 
  def change_mac(interface, new_mac):
      print("[+] Changing MAC address for " + interface + " to "+ new_mac)
      subprocess.run("ifconfig "+interface+" down", shell=True)
      subprocess.run("ifconfig "+interface+" hw ether "+new_mac, shell=True)
      subprocess.run("ifconfig "+interface+" up",shell=True)
  options= get_arguments()

  ifconfig_result = subprocess.check_output(["ifconfig", options.interface])
  print(ifconfig_result)

Python2输出:

eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 10.0.2.4  netmask 255.255.255.0  broadcast 10.0.2.255
        inet6 AAAAA   prefixlen 64  scopeid 0x20<link>
        ether AAAAA  txqueuelen 1000  (Ethernet)
        RX packets 12176  bytes 17869942 (17.0 MiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 3507  bytes 213850 (208.8 KiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

但是我的输出显示了

b'eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500\n        inet 10.0.2.4  netmask 255.255.255.0  broadcast 10.0.2.255\n        inet6 AAAAA prefixlen 64  scopeid 0x20<link>\n        ether AAAAA  txqueuelen 1000  (Ethernet)\n        RX packets 12179  bytes 17870182 (17.0 MiB)\n        RX errors 0  dropped 0  overruns 0  frame 0\n        TX packets 3510  bytes 214090 (209.0 KiB)\n        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0\n\n'

1 个答案:

答案 0 :(得分:0)

在python 3中,您不仅拥有香草字符串,而且还有一个存储转义序列的二进制字符串,'\n'代表换行符。要像正常使用该字符串一样对其进行解码。最小示例:

>>> string = b"Hello \n World"
>>> print(string)
>>> b'Hello \n World'
>>> string = string.decode('ascii')  # sring decoding
>>> print(string)
    Hello 

    World
>>> 

也看看这个问题:How to convert 'binary string' to normal string in Python3?