亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Ping的Python控制臺和文本輸出,包括\ n \ r

Ping的Python控制臺和文本輸出,包括\ n \ r

慕絲7291255 2021-03-10 14:12:29
我不知道發生了什么,但是當我在控制臺或文本文件上打印時,換行符(\ n)無法正常運行,而是顯示在字符串中。知道如何在控制臺和文本文件中避免這種情況嗎?我的代碼:import subprocesshosts_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 timed out.\r\nRequest timed out.\r\n\r\nPing statistics for 192.168.0.1:\r\n    Packets: 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 timed out.\r\nRequest timed out.\r\n\r\nPing statistics for 192.168.0.2:\r\n    Packets: 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 timed out.\r\nRequest timed out.\r\n\r\nPing statistics for 192.168.0.3:\r\n    Packets: 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 timed out.\r\nRequest timed out.\r\n\r\nPing statistics for 192.168.0.4:\r\n    Packets: 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 timed out.\r\nReply from 3.112.3.214: Destination host unreachable.\r\n\r\nPing statistics for 192.168.0.5:\r\n    Packets: Sent = 3, Received = 1, Lost = 2 (66%loss),'b''主機文件:192.168.0.1192.168.0.2192.168.0.3192.168.0.4192.168.0.5
查看完整描述

2 回答

?
一只甜甜圈

TA貢獻1836條經驗 獲得超5個贊

問題是您要打印出Python 3bytes對象,該Python無法自動轉換為str對象,因為無法確定字符編碼是什么。


您必須使用bytes對象的decode()方法將其轉換為字符串,告訴Python編碼是什么...


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()


查看完整回答
反對 回復 2021-03-29
  • 2 回答
  • 0 關注
  • 216 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號