Python中'print'的实现

问题描述 投票:2回答:1

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

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个回答
2
投票

print是Python 3中的内置函数。大多数内置函数都是用C实现的(无论如何,在默认的CPython解释器中),print也不例外。实现是builtin_print中的Python/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/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()
© www.soinside.com 2019 - 2024. All rights reserved.