I/O注册表 (skbio.io.registry

Classes

IORegistry \()

要创建注册表的格式和实现。

Format(name[, encoding, newline])

定义可以注册读卡器/写入程序/嗅探器的格式。

功能

create_format(self, *args, **kwargs)

创建新文件格式的简单工厂。

例外情况

DuplicateRegistrationError 

函数已在中注册时引发skbio.io公司

InvalidRegistrationError 

如果函数不符合其注册的预期API,则引发。

为scikit-bio创建新格式

scikit-bio使向其I/O注册表添加新文件格式变得简单。scikit-bio保持着 IORegistry 类称为 io_registry . 所有scikit-bio文件格式都在这里注册。你也可以实例化他们自己的 IORegistry ,但这不是本教程的重点。

创建新格式的第一步是在中添加子模块 skbio/io/format/ 以正在实现的文件格式命名。例如,如果要实现的格式调用 myformat 然后创建一个名为 skbio/io/format/myformat.py .

下一步是导入 create_format() 出厂日期 skbio.io . 这将允许您创建一个新的 Format 对象 io_registry 会知道的。

理想情况下,你应该说出 create_format() 作为你的文件名。例如:

from skbio.io import create_format

myformat = create_format('myformat')

这个 myformat 对象是我们将用来注册新功能的。在这一点上,您应该回避您的格式是二进制还是文本。如果您的格式是二进制,则 create_format() 电话应该是这样的:

myformat = create_format('myformat', encoding='binary')

或者,如果您的格式是文本并且具有特定的编码或换行处理,您也可以指定:

myformat = create_format('myformat', encoding='ascii', newline='\n')

这将确保我们的注册表将打开默认编码为的文件 'ascii' 对于 'myformat' 希望所有的新行 'n' 字符。

完成这些细节之后,我们就可以注册格式的实际功能了(例如,嗅探器、读卡器和编写器)。

要创建嗅探器,只需在嗅探器函数上装饰以下内容:

@myformat.sniffer()
def _myformat_sniffer(fh):
    # do something with `fh` to determine the membership of the file

有关嗅探器函数的更多详细信息,请参见 Format.sniffer() .

创建阅读器非常相似,但有一个区别:

@myformat.reader(SomeSkbioClass)
def _myformat_to_some_skbio_class(fh, kwarg1='default', extra=FileSentinel):
    # parse `fh` and return a SomeSkbioClass instance here
    # `extra` will also be an open filehandle if provided else None

这里我们将一个函数绑定到一个特定的类。我们还演示了如何使用FileSentinel对象向注册表指示此读取器可以获取辅助文件,这些文件应该以与主文件相同的方式进行处理。有关读卡器功能的更多详细信息,请参阅 Format.reader() .

创建一个作家也是一样的:

@myformat.writer(SomeSkbioClass)
def _some_skbio_class_to_myformat(obj, fh, kwarg1='whatever',
                                  extra=FileSentinel):
    # write the contents of `obj` into `fh` and whatever else into `extra`
    # do not return anything, it will be ignored

这和 reader 相反地,我们也会接收作为第一个参数而不是文件(即第二个参数)的对象。有关writer函数的详细信息,请参见 Format.writer() .

备注

当在读写器中产生错误时,错误应该是 FileFormatError 特定于您的新格式。

一旦您对功能感到满意,您需要确保 skbio/io/__init__.py 包含新子模块的导入,以便执行装饰器。添加函数 import_module('skbio.io.format.myformat') 将您的模块名称添加到现有列表中。

备注

因为scikit-bio处理所有的I/O样板,所以您只需要对 readerswriterssniffers .

保留关键字参数

定义new时不能使用以下关键字args readerswriters 因为它们对登记系统已经有了特殊的意义:

  • format

  • into

  • verify

  • mode

  • encoding

  • errors

  • newline

  • compression

  • compresslevel

以下尚未使用,但也应避免:

  • auth

  • user

  • password

  • buffering

  • buffer_size

  • closefd

  • exclusive

  • append