syslog を受信してテキスト ファイルに追加するために使用しているスクリプトを次に示します。
# Receives packets on udp port 514 and
# writes to syslog.txt
from socket import *
# Set the socket parameters
host = "myhost"
port = 514
buf = 1024
addr = (host,port)
# Create socket and bind to address
UDPSock = socket(AF_INET,SOCK_DGRAM)
UDPSock.bind(addr)
# Receive messages
while 1:
data,addr = UDPSock.recvfrom(buf)
if not data:
print "Client has exited!"
break
else:
print "\nReceived message '", data,"'"
# This will create a new file or overwrite an existing file.
with open("C:\syslog.txt", "a") as myfile:
myfile.write(str(data))
# Close socket
UDPSock.close()
スクリプトは正常に機能し、テキストがファイルに追加されます。私はそれを見て、よく読んでいます。しかし、Python を閉じた瞬間、その txt ファイルのデータは意味不明なテキストに変換されます。理由はありますか?ソケットデータをファイルに追加する前に何か他のことをする必要がありますか?
ありがとう。