This question already has an answer here:
- Convert bytes to a string? 16 answers
I dont know what is happening, but when I am printing to the console or to a text file, the newline (\n) is not functioning but rather showing in the string. Any idea how to avoid this in both the console and the text file?
My code:
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()
Output:
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''
Hosts File:
192.168.0.1
192.168.0.2
192.168.0.3
192.168.0.4
192.168.0.5