Python console and text output from Ping including \\n\\r [duplicate]

半世苍凉 提交于 2019-12-05 21:52:37
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()

Gives me:

[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

The problem is that you're trying to print out a Python 3 bytes object, which Python cannot automatically convert to a str object, because it can't be certain what the character encoding is.

You'll have to convert it to a string, telling Python what the encoding is, using the bytes object's decode() method...

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()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!