python os

os.name

The name of the operating system dependent module imported.
Windows 返回 nt; Linux 返回posix

os.open() v.s. open() v.s. io.open()

os

下图摘自 fasionchan 同学 的 Linux文件描述符

fd.png

总之呢,file descriptor 只是 一个非负整数,用作文件描述符表的索引;

file object:An object exposing a file-oriented API (with methods such as read() or write()) to an underlying resource.File objects are also called file-like objects or streams.There are actually three categories of file objects: raw binary files, buffered binary files and text files.

  • os.open(path, flags, mode=0o777, *, dir_fd=None)
    Return the file descriptor for the newly opened file.

  • io.open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
    This is an alias for the builtin open() function.

  • open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
    Open file and return a corresponding file object.

  • class io.IOBase

    • fileno()
      Return the underlying file descriptor (an integer) of the stream if it exists.
  • os.fdopen(fd, *args, **kwargs)
    Return an open file object connected to the file descriptor fd.

Lib/os.py 中的定义:

def fdopen(fd, *args, **kwargs):
    if not isinstance(fd, int):
        raise TypeError("invalid fd type (%s, expected integer)" % type(fd))
    import io
    return io.open(fd, *args, **kwargs)

Tornado v1.0.0 源码

  self._waker_reader = os.fdopen(r, "r", 0)
  self._waker_writer = os.fdopen(w, "w", 0)

由上面可知,os.fdopen()调用的是 io.open(), 故会调用 open(file, mode='r', buffering=-1, ...)
其中,

  • mode: mode is an optional string that specifies the mode in which the file is opened. It defaults to 'r' which means open for reading in text mode.

    • r: open for reading (default)
      w: open for writing, truncating the file first
      x: open for exclusive creation, failing if the file already exists
      a: open for writing, appending to the end of the file if it exists
      b: binary mode
      t: text mode (default)
      +: open a disk file for updating (reading and writing)
      U: universal newlines mode (deprecated)
  • buffering: buffering is an optional integer used to set the buffering policy. Pass 0 to switch buffering off (only allowed in binary mode), 1 to select line buffering (only usable in text mode), and an integer > 1 to indicate the size in bytes of a fixed-size chunk buffer. When no buffering argument is given, 则默认分配。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容