代码之家  ›  专栏  ›  技术社区  ›  Hatshepsut

当sys.stdout不是[duplicate]时意味着什么

  •  0
  • Hatshepsut  · 技术社区  · 6 年前

    我可以沉默和恢复 sys.stdout 这种方式:

    import sys
    sys.stdout = None
    print('hello')  # does not write to stdout
    sys.stdout = sys.__stdout__
    print('hello')  # writes to stdout
    

    我知道我最好用 contextlib.redirect_stdout 这可能做了一些类似的事情,但我的问题是:为什么上面的代码工作?

    我以为python会调用 sys.stdout.write() 所以不管我换什么 系统标准输出 应该有一个 write 方法(例如。 io.StringIO )至少。

    0 回复  |  直到 6 年前
        1
  •  12
  •   user2357112    6 年前

    print has an explicit check for None .

        /* sys.stdout may be None when FILE* stdout isn't connected */
        if (file == Py_None)
            Py_RETURN_NONE;