【问题标题】:Implementation of 'print' in Python在 Python 中实现“打印”
【发布时间】:2020-03-21 05:23:39
【问题描述】:

我只是好奇内置函数“print”在 Python3 中是如何在幕后工作的。因此,下面的代码 sn-p 是我尝试编写自己的打印函数,但我不确定它是否准确地代表了实际的“打印”的工作原理:

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()

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

【问题讨论】:

标签: python python-3.x function built-in


【解决方案1】:

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

另一方面,PyPy 解释器是在 Python 的一个子集中实现的,因此它在pypy/module/__builtin__/app_io.py 中有一个用 Python 编写的 print 函数,可以在这里看到:https://bitbucket.org/pypy/pypy/src/5da45ced70e515f94686be0df47c59abd1348ebc/pypy/module/builtin/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()

【讨论】:

    猜你喜欢
    • 2020-06-18
    • 1970-01-01
    • 2017-08-10
    • 2012-11-17
    • 2013-01-02
    • 2018-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多