简体   繁体   中英

Python script writes gibberish to file

Here's a script I am using to receive syslog and append it to a text file:

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

Scripts works fine and text is appended to file. I see it and it's read well. However, the moment I close python, that txt file data is translated to gibberish text. Any ideas why? Am I supposed to do something else before appended socket data to a file?

Thanks.

You're not parsing the syslog packets. Syslog is a protocol ; it's not just plain text. Data characters are most likely ending up in your file, which may be tripping some automatic character detection.

这可能直接完成您想要实现的目标(解析syslog协议并将其转储): http : //pypi.python.org/pypi/loggerglue/0.9

I was going to suggesting doing open("C:\\syslog.txt", "at") instead of open("C:\\syslog.txt", "a"), but re-reading the python dox, text is the default (unlike with C, where my memory says that binary is the default which leads to issues when running on windows).

My other suggestion would be to put a plain text header at the top of the file when you first create it; not sure what you're using to read the file after, but Notepad and Wordpad use some heuristics to figure out what UTF-8 or other encoding is being used, and I've definitely seen cases where this fails badly. (Search wordpad BOM guess)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM