1 questions
In the background field, often using Python to do some simple service, achieve faster, more flexible changes, compared to C + +, the cost is much lower. As a back-office service, you want the service to be able to output log data in real-time for observation while observing the service's performance. Before I wrote a service in Python, I found that I didn't write the data to disk in real time, so that when I looked at the data, I found that the actual behavior was successful, but the log was not recorded.
2 Cause analysis and solution
Example code:
#!/usr/bin/env python#-*-CODING:GBK-*-ImportTIMEFD= Open ("a.txt","a") I=0 while1: buf="a\n"fd.write (BUF) time.sleep (1) I= i + 1ifI > 10: Breakfd.close ()
The function of the code is simple, and every second writes "a" to the file a.txt. In the run, it is found that after 10 seconds of running, the file a.txt will actually finish writing the data. The reason is that the Python implementation, after calling write, simply writes the data to the kernel buffer, and does not actually write the data to disk, and the data is written to disk only if close is called or if the kernel buffer is full .
We look at it abstractly, and for our service, we usually write code like this:
# !/usr/bin/env python # -*-CODING:GBK-*- Import = 0 while 1: # work do_something () # flush Buffer, write data to disk, FD for open file handle, assuming you have opened Fd.flush () in the system
For us, every time the service do_something, we want to see the output in real time. The flush function is called to output the data to disk after each loop, so that the log output can be observed in real time.
Of course, the frequent use of this function, to consider performance problems, the system frequently writes data to disk, is more CPU-intensive, for the service of a small number of cases, so the use is more convenient.
Python uses the flush function to write the buffer data immediately to disk