Python 中“打印”的实现

den*_*niz 3 python function built-in python-3.x

我只是好奇 Python3 中的内置函数 'print' 是如何在幕后工作的。因此,以下代码片段是我尝试编写自己的打印功能,但我不确定它是否准确表示实际“打印”的工作方式:

import os
import sys
def my_print(*args, **kwargs):
    sep = kwargs.get('sep', ' ')
    end = kwargs.get('end', os.linesep)
    if end is None:
        end = os.linesep
    file = kwargs.get('file', sys.stdout)
    flush = kwargs.get('flush', False)
    file.write('%s%s' % (sep.join(str(arg) for arg in args), end))
    if flush:
        file.flush()
Run Code Online (Sandbox Code Playgroud)

如果有人知道内置“打印”的工作原理,请评估我的版本的准确性并指出任何不足之处,我将不胜感激。

nne*_*neo 6

print是 Python 3 中的内置函数。大多数内置函数都是用 C 实现的(无论如何在默认的 CPython 解释器中),print也不例外。实现builtin_printPython/bltinmodule.c,可以在这里看到:https : //github.com/python/cpython/blob/v3.8.0/Python/bltinmodule.c#L1821

另一方面,PyPy 解释器是在 Python 的一个子集中实现的,因此它有一个print用 Python 编写的函数pypy/module/__builtin__/app_io.py,可以在这里看到:https : //bitbucket.org/pypy/pypy/src/5da45ced70e515f94686be0df47c59abd1348ebc/pypy /module/内置/app_io.py#lines-59

这是相关的代码;它相当短:

def print_(*args, **kwargs):
    r"""print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)

    Prints the values to a stream, or to sys.stdout by default.
    Optional keyword arguments:
    file:  a file-like object (stream); defaults to the current sys.stdout.
    sep:   string inserted between values, default a space.
    end:   string appended after the last value, default a newline.
    flush: whether to forcibly flush the stream.
    """
    fp = kwargs.pop("file", None)
    if fp is None:
        fp = sys.stdout
        if fp is None:
            return
    def write(data):
        fp.write(str(data))
    sep = kwargs.pop("sep", None)
    if sep is not None:
        if not isinstance(sep, str):
            raise TypeError("sep must be None or a string")
    end = kwargs.pop("end", None)
    if end is not None:
        if not isinstance(end, str):
            raise TypeError("end must be None or a string")
    flush = kwargs.pop('flush', None)
    if kwargs:
        raise TypeError("invalid keyword arguments to print()")
    if sep is None:
        sep = " "
    if end is None:
        end = "\n"
    for i, arg in enumerate(args):
        if i:
            write(sep)
        write(arg)
    write(end)
    if flush:
        fp.flush()
Run Code Online (Sandbox Code Playgroud)