\r\n 在我的文本文件中显示为字符串
我对Python完全是个新手,但在使用Cisco等命令行界面方面有不少经验。我决定把Python当作我的主要脚本工具。不过,我第一次尝试的时候失败得很惨,尽管我大部分代码都是抄的。
我正在对一系列主机进行ping测试。这样做的目的是:1. 验证这些主机是否在线,2. 获取它们的IP地址。
我在网上找到的脚本经过一些调整后在3.4版本上可以运行。
显示效果正如我所期望的那样完美。不过,它写入的文件只有一长行,里面的\r\n看起来就像是文本的一部分。这是代码,还有屏幕显示和写入文件的示例。
import sys
import os
import platform
import subprocess
import threading
import pexpect
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()
屏幕显示效果完美
Pinging HOST7.foo [10.180.43.209] with 32 bytes of data:
Reply from 10.180.43.209: bytes=32 time=81ms TTL=60
Reply from 10.180.43.209: bytes=32 time=56ms TTL=60
Reply from 10.180.43.209: bytes=32 time=56ms TTL=60
Notepad++显示为单行,并且可见的\r\n(其他编辑器也是如此)
b'Pinging host7.foo [10.180.43.11] with 32 bytes of data:\r\nReply from 10.18.43.11: bytes=32 time=555ms TTL=60\r\nReply from 10.18.43.11: bytes=32 time=140ms TTL=60\r\nReply from 10.180.43.11: bytes=32 time=139ms TTL=60\r\n\r\nPing statistics for 10.180.43.11:\r\n Packets: Sent = 3, Received = 3, Lost = 0 (0% loss),\r\nApproximate round trip times in milli-seconds:\r\n Minimum = 139ms, Maximum = 555ms, Average = 278ms'b''b'Pinging host9.foo [10.180.43.25] with 32 bytes of data:\r\nReply from
求求你,欧比旺·肯诺比……你是我唯一的希望……
1 个回答
3
我在Ubuntu上用Python 2.7再次检查了这段代码,结果运行得很好,只需要加上'\n'或者os.linesep。
在Python 3.2中,subprocess.communicate会返回一个字节数组。
使用out.decode()可以把它转换成字符串。
[下面是Python 2.7的内容]
string.strip()默认会去掉行末的换行符。
"Hello\n".strip()
返回
'Hello'
使用
output.write(str(out + '\n'))
或者
output.write(str(out + os.linesep))
[下面是Python 3.X的内容]
output.write(out.decode() + os.linesep)