Skip to main content
 首页 » 编程设计

python之如何设置文件缓冲参数

2024年11月01日13Terrylee

使用 Python 脚本在 shell 中运行一个漫长而耗时的数字运算过程。在脚本中,为了指示进度,我插入了偶尔的打印命令,如

#!/usr/bin/env python3 
#encoding:utf-8 
print('Stage 1 completed') 

通过

触发 shell 中的脚本
user@hostname:~/WorkingDirectory$chmod 744 myscript.py && nohup ./myscript.py& 

它将输出重定向到 nohup.out,但在整个脚本完成之前我看不到输出,这可能是因为标准输出缓冲。那么在这种情况下,我如何以某种方式调整缓冲参数以定期检查进度?基本上,我想要零缓冲,以便在 python 脚本中发出打印命令后,它就会出现在 nohup.out 上。那可能吗?

我知道这是一个新手问题,除了确切的解决方案外,任何易于理解的相关 Material 引用(这将帮助我掌握 shell 的缓冲方面,而无需深入内核或硬件级别)将会非常有用也很感激。

如果它很重要,我在 x86_64 上使用 #54~16.04.1-Ubuntu

请您参考如下方法:

Python 针对读取和打印大量数据进行了优化。
所以默认情况下,Python 解释器的标准输入和输出是缓冲的。

我们可以通过一些方式覆盖这个行为:

  1. 使用带有选项 -u 的解释器 python。

来自 man python:

       -u     Force stdin, stdout and stderr to be totally unbuffered.  On systems where it matters, also put stdin,  stdout  and  stderr  in 
              binary  mode.   Note  that  there  is  internal  buffering in xreadlines(), readlines() and file-object iterators ("for line in 
              sys.stdin") which is not influenced by this option.  To work around this, you will want to use "sys.stdin.readline()" inside  a 
              "while 1:" loop. 
 

在 shell 中运行脚本:

nohup python -u ./myscript.py& 

或者将脚本的 shebang 行修改为 #!/usr/bin/python -u 然后运行:

nohup ./myscript.py& 
  1. 使用 shell 命令 stdbuf 关闭缓冲流

参见 man stdbuf。

为输出设置无缓冲流:

stdbuf --output=0 nohup ./myscript.py& 

为输出和错误设置无缓冲流:

stdbuf -o0 -e0 nohup ./myscript.py&