📝 Update README.md with Python print buffering documentation and solutions
This commit is contained in:
@@ -79,3 +79,23 @@ if __name__ == "__main__":
|
||||
```shell
|
||||
./show_myip.py
|
||||
```
|
||||
|
||||
<br>
|
||||
|
||||
在 Python 中,print() 函数默认会对输出进行缓存(buffering)。
|
||||
|
||||
```python
|
||||
import time
|
||||
|
||||
for i in range(5, 0, -1):
|
||||
# end="" 让它不换行,flush=True 强制立即刷新缓存
|
||||
print(f"\rcountdown: {i}", end="", flush=True)
|
||||
time.sleep(1)
|
||||
print("\ndone!")
|
||||
```
|
||||
|
||||
通过设置环境变量也可以禁止缓存:
|
||||
```shell
|
||||
export PYTHONUNBUFFERED=1
|
||||
```
|
||||
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
import io
|
||||
import sys
|
||||
from time import sleep
|
||||
|
||||
# 将标准输出设置为无缓存模式
|
||||
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, write_through=True)
|
||||
|
||||
if __name__ == "__main__":
|
||||
# 之后的 print 都不再需要写 flush=True 了
|
||||
print("这条消息会立即输出")
|
||||
Reference in New Issue
Block a user