Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Python had few people walking through the pit


May 31, 2021 Article blog


Table of contents


The article comes from the public number: Python Technology, author of Paisen Sauce

There is no doubt that print function is the most commonly used function in our day-to-day, whether it is formatting the output or printing intermediate variables for debugging, there is almost no print can not catch the work.

But the last time A sauce was almost print to the pit.

Where did the pit come from?

Initially trying to add a progress display to one of your own command-line gadgets, you use the threading module to implement threading one thread to execute the actual logic, and the other thread to print the current progress.

 Python had few people walking through the pit1

Based on our years of experience with command lines, it's generally not good to print within a line, and Python's print print prints a line break at the end by default.

Fortunately, print also provides an interface to change the end character of the print, which can be print by specifying the end parameter of the print

So I hum and dry, changing the print("#") to print print("#", end="")

Something like this:

import time
import threading


def print_sharp():
    while True:
        time.sleep(0.5)
        print("#", end="")




t1 = threading.Thread(target=print_sharp)
t1.setDaemon(True)
t1.start()


time.sleep(5)

Which way to think, such a change but a big problem: progress can not be printed in real time.

That is, it should have been printed one by one during program execution that the # were no longer obedient, # but were output to the console once after the entire program had been executed.

It grows up and gets ugly.

 Python had few people walking through the pit2

What do I want from you?

What's the problem?

At first A sauce thought it was a multithreaded problem, silly everywhere looking for information to "support" their various guesses - in hindsight is too silly to say now or hahaha

The lesson of this is: Don't be self-righteous, but solve problems down-to-earth and treat every detail with an open mind.

In fact, the reason we don't see real-time output is because we change the end character of print

To minimize I/O operations, Python has a mechanism for caching output characters as much as possible and outputting the contents of the buffer into the appropriate stream at once when a string ends, line breaks, or forces a buffer to be flushed.

And where we changed it was to remove the print default line break, so every print would have triggered a buffer refresh, and now it has not been triggered until the end of the program.

Well, knowing what's wrong, we're looking for information again, and we hear that sys.stdout.flush can force a flush of the standard output buffer, so after print sys.stdout.flush() is added.

What do you want? Is that really good?

 Python had few people walking through the pit3

These can be knowledge points, quickly write down to write down, to test

Let's look at the official documentation for print which is prototyped as:

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

According to the description below, whether the output of print in Python is buffered depends on two parameters: file and flush

Some types of file require buffering, such as sys.stdout while others do not, such as sys.stderr

For flush parameters, whether to buffer depends on file when its value is False (default), and when its value is True the buffer is forced to flush.

Let's modify the print call in the sample call:

import sys
import time
import threading




def print_sharp():
    while True:
        time.sleep(0.5)
        print("#", end="", flush=True)




t1 = threading.Thread(target=print_sharp)
t1.setDaemon(True)
t1.start()


time.sleep(5)

 Python had few people walking through the pit4

Real-time printing of progress is also possible.

In addition, there is a way to add a -u option when calling a program, which can also enable real-time flushing of the buffer:

$ python -u no_flush.py

 Python had few people walking through the pit5

Of course, this method is not very recommended, after all, can not make any presets for the user of the program.

summary

This article is a tap-in transcript of A sauce, documenting a rare problem in Python that few people encounter.

In general, to be a true Python programmer, it is not enough to simply master basic grammar and some tricks, or to have some understanding of Python itself.

After all, if swordsmen are not familiar with their swords, how to walk rivers and lakes?

These are W3Cschool编程狮 about Python's few people walking through the pits, I hope to help you.