为什么python imghdr测试函数将文件作为参数?

2024-05-15 18:03:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在查看imghdr模块的源代码,它是python标准库的一部分(我使用2.7)。这个结构非常简单,what函数遍历一个名为test_filetype的函数列表,如果传入的文件与任何测试匹配,则返回该文件类型的字符串。在

所有test_filetype函数都有两个参数,h和{}。h是一个包含f.read(32)内容的字符串,f是打开的文件对象。没有一个test_filetype函数实际上将f用于任何事情。在

为什么test_filetype函数集都采用从未使用过的参数?在


Tags: 模块文件函数字符串test列表read参数
1条回答
网友
1楼 · 发布于 2024-05-15 18:03:45

我想这是为了允许将自定义函数添加到imghdr.tests。从documentation of ^{} module-

You can extend the list of file types imghdr can recognize by appending to this variable:

imghdr.test

A list of functions performing the individual tests. Each function takes two arguments: the byte-stream and an open file-like object. When what() is called with a byte-stream, the file-like object will be None.

The test function should return a string describing the image type if the test succeeded, or None if it failed.

从文档中可以看出,imghdr模块允许扩展到tests列表。我认为添加参数f可以用于添加到这个列表中的这些自定义函数。在

看看^{} function-

if h is None:
    if isinstance(file, basestring):
        f = open(file, 'rb')
        h = f.read(32)
    else:
        location = file.tell()
        h = file.read(32)
        file.seek(location)

可以看出,当我们向what()函数发送文件名时,它只读取文件的前32个字节,只发送test函数的h参数中的32个字节,我认为附加的f参数可能适用于第一个32字节不足以确定图像格式的情况(尤其是对于自定义测试)。在

相关问题 更多 >