【问题标题】:Is sys.stderr a block device or character device in Python3?sys.stderr 是 Python3 中的块设备还是字符设备?
【发布时间】:2013-01-10 02:24:50
【问题描述】:

在 C 语言中,如果我写这样的代码:

#include <stdio.h>
#include <unistd.h>
int main() 
{
    while(1)
    {
        fprintf(stdout,"hello-std-out");
        fprintf(stderr,"hello-std-err");
        sleep(1);
    }
    return 0;
}

标准输出不会显示,因为它是块设备。但是 stderr 会显示,因为它不是。

但是,如果我在 Python3 中编写类似的代码:

import sys
import time
if __name__ == '__main__':
    while True:
        sys.stdout.write("hello-std-out")
        sys.stderr.write("hello-stderr")
        time.sleep(1)

如果我不刷新这些缓冲区,stdout 和 stderr 都不会显示。这是否意味着 sys.stderr 也是 Python 中的块设备?

【问题讨论】:

  • 块/字符指定与缓冲没有严格的关系。请参阅维基百科 device file 条目。
  • 默认情况下 Python 缓冲标准输出。您可以使用 -u 标志强制 stdin、stdout 和 stderr 完全无缓冲:python -u test.py
  • @unutbu 我尝试添加-u,但stderr仍然无法显示
  • 这很有趣。无论我是否使用-u,我都会看到 stderr(使用 Ubuntu 和 gnome 终端)。
  • @pst 是对的:缓冲区和块不是同义词。大多数系统为 STDOUT/STDERR 使用字符设备,但它们缓冲 STDOUT。 STDERR 往往是无缓冲的,这就是为什么你有时会混淆 STDOUT 和 STDERR 的交织。

标签: python c linux buffer device


【解决方案1】:

如果您没有看到 stderr,那么您在 Python3 上,其中文本 IO 层在连接到 tty 时为行缓冲,否则为块缓冲,无论 -u 选项。

缓冲问题与字符/块设备无关。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多