python - Python 的 `file.read` 函数如何计算出文件的大小?

标签 python c python-2.7 cpython

我正在查看 Python-2.7.6 的源代码来解决这个问题。

Objects/fileobject.c中,第1052行,有一个叫做file_read的函数,我猜它对应于函数readPython 中的文件对象上。

在同一文件的第 1067 行,我看到以下行。请注意,bytesrequested 在函数中进一步使用,以确定要分配用于存储文件的缓冲区的大小。

 if (!PyArg_ParseTuple(args, "|l:read", &bytesrequested))

看起来请求的字节数以某种方式编码在 args 中,其类型为 PyObject*。因此,继续搜索的自然位置是找出调用 file_read 的位置。

但是,我无法在整个 Python 源代码树(递归 grep)中找到实际调用 file_read 的地方,因此我无法继续跟踪以找出 bytesrequested 实际上是计算出来的。 file_read 是否以某种方式在源代码树的不同部分以不同的名称调用?

最佳答案

line 2114

file_read 是 python 的 file.read 方法。 C 代码中的 args 是您传递给 file.read 的参数。 bytesrequested 是您作为参数传递给 file.read

的任何内容
with open('file') as fin:
    fin.read(5)  # bytesrequested will be 5.

关于python - Python 的 `file.read` 函数如何计算出文件的大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20604424/

相关文章:

python - 在列表中查找子列表的索引

c - 怎么x?y :a? b :c will be evaluated?

Python for 循环执行

c socket发送大文件时出现broken pipe错误

c - C、Linux中不同进程线程的同步

python - setuptools 在安装过程中发现错误的包

python为数组创建卷积函数

python - 如何使用 Django Rest Framework 将 url 字段添加到序列化程序

python - 不同版本的 Python 中的文本格式

python - 使用谷歌应用程序引擎部署 Bottle 应用程序时出现问题