【问题标题】:Python console and text output from Ping including \n\r [duplicate]Ping 的 Python 控制台和文本输出,包括 \n\r [重复]
【发布时间】:2013-05-27 13:26:14
【问题描述】:

我不知道发生了什么,但是当我打印到控制台或文本文件时,换行符 (\n) 不起作用,而是显示在字符串中。知道如何在控制台和文本文件中避免这种情况吗?

我的代码:

import subprocess

hosts_file = open("hosts.txt","r")
lines = hosts_file.readlines()

for line in lines:
    line = line.strip()
    ping = subprocess.Popen(["ping", "-n", "3",line],stdout = subprocess.PIPE,stderr = subprocess.PIPE)
    out, error = ping.communicate()
    out = out.strip()
    error = error.strip()
    output = open("PingResults.txt",'a')
    output.write(str(out))
    output.write(str(error))
    print(out)
    print(error)
hosts_file.close()

输出:

b'Pinging 192.168.0.1 with 32 bytes of data:\r\nRequest timed out.\r\nRequest ti
med out.\r\nRequest timed out.\r\n\r\nPing statistics for 192.168.0.1:\r\n    Pa
ckets: Sent = 3, Received = 0, Lost = 3 (100% loss),'
b''
b'Pinging 192.168.0.2 with 32 bytes of data:\r\nRequest timed out.\r\nRequest ti
med out.\r\nRequest timed out.\r\n\r\nPing statistics for 192.168.0.2:\r\n    Pa
ckets: Sent = 3, Received = 0, Lost = 3 (100% loss),'
b''
b'Pinging 192.168.0.3 with 32 bytes of data:\r\nRequest timed out.\r\nRequest ti
med out.\r\nRequest timed out.\r\n\r\nPing statistics for 192.168.0.3:\r\n    Pa
ckets: Sent = 3, Received = 0, Lost = 3 (100% loss),'
b''
b'Pinging 192.168.0.4 with 32 bytes of data:\r\nRequest timed out.\r\nRequest ti
med out.\r\nRequest timed out.\r\n\r\nPing statistics for 192.168.0.4:\r\n    Pa
ckets: Sent = 3, Received = 0, Lost = 3 (100% loss),'
b''
b'Pinging 192.168.0.5 with 32 bytes of data:\r\nRequest timed out.\r\nRequest ti
med out.\r\nReply from 3.112.3.214: Destination host unreachable.\r\n\r\nPing st
atistics for 192.168.0.5:\r\n    Packets: Sent = 3, Received = 1, Lost = 2 (66%
loss),'
b''

主机文件:

192.168.0.1
192.168.0.2
192.168.0.3
192.168.0.4
192.168.0.5

【问题讨论】:

    标签: python subprocess ping popen python-3.3


    【解决方案1】:

    问题是您试图打印出 Python 3 bytes 对象,Python 无法自动将其转换为 str 对象,因为它无法确定字符编码是什么。

    您必须将其转换为字符串,告诉 Python 编码是什么,使用 bytes 对象的 decode() 方法...

    import subprocess
    
    hosts_file = open("hosts.txt","r")
    lines = hosts_file.readlines()
    
    for line in lines:
        line = line.strip()
        ping = subprocess.Popen(["ping", "-n", "3",line],stdout = subprocess.PIPE,stderr = subprocess.PIPE)
        out, error = ping.communicate()
        out = out.strip()
        error = error.strip()
        output = open("PingResults.txt",'a')
        output.write(str(out))
        output.write(str(error))
        print(out.decode('utf-8'))
        print(error.decode('utf-8'))
    hosts_file.close()
    

    【讨论】:

      【解决方案2】:
      import subprocess
      
      hosts_file = open("hosts.txt","r")
      lines = hosts_file.readlines()
      hosts_file.close()
      
      for line in lines:
          ping = subprocess.Popen(["ping", "-n", "3",line.strip()], stdout=subprocess.PIPE, stderr=subprocess.POPEN)
          with open('PingResults.txt', 'ab') as fh:
              for line in ping.stdout.readlines():
                  fh.write(line)
          ping.stdout.close()
      

      给我:

      [torxed@faparch ~]$ python test.py && cat PingResults.txt 
      PING 127.0.0.1 (127.0.0.1) 56(84) bytes of data.
      64 bytes from 127.0.0.1: icmp_seq=1 ttl=64 time=0.016 ms
      64 bytes from 127.0.0.1: icmp_seq=2 ttl=64 time=0.023 ms
      64 bytes from 127.0.0.1: icmp_seq=3 ttl=64 time=0.035 ms
      
      --- 127.0.0.1 ping statistics ---
      3 packets transmitted, 3 received, 0% packet loss, time 1999ms
      rtt min/avg/max/mdev = 0.016/0.024/0.035/0.009 ms
      PING 192.168.0.1 (192.168.0.1) 56(84) bytes of data.
      
      --- 192.168.0.1 ping statistics ---
      3 packets transmitted, 0 received, 100% packet loss, time 2008ms
      

      【讨论】:

      • 这适用于文件输出,但如果我在 fh.write 下添加 print(line),则输出行以 ab' 开头并以 \r\n' 结尾。
      • 那是因为在Python3.X 控制台执行的输出是一个字节数组,这意味着你必须做print(str(line))
      • 甚至:print(''.join('%02x' % ord(byte) for byte in line))
      • 我之前尝试过 str(line) 并给出了相同的结果。我从未使用过 ord 函数,但是您发布的内容给了我一个错误,说 ord() 预期的字符串长度为 1,但找到了 int。
      • 我从 Aya 的代码中提取了一部分来解决它。我刚刚添加了 print(str(line.decode('utf-8')))
      猜你喜欢
      • 2016-11-15
      • 2020-02-25
      • 2017-02-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-03
      • 1970-01-01
      相关资源
      最近更新 更多