一个遍历tar档案的库,通过处理列表和解压简化了使用。
tarwalker的Python项目详细描述
摘要
tarwalker提供了一种方法,可以轻松地扫描类似于 os.walk, 处理压缩文件、通过目录递归和扫描 在tarfiles内。
图书馆很稳定,变化很少。它有很好的记录 具有完整的单元测试(100%代码覆盖率),并得到维护。
概述
有关此库的注释:
- 它可以遍历压缩或未压缩的文件和tarfiles(以及可选的 目录),一次处理一个目标文件。
- 它使用一对回调来避免打开或解压缩文件
不感兴趣的:
- 首先使用文件的元数据调用matcher,然后 如果要使用文件,则返回true。
- 如果是,则用元数据调用handler,然后调用matcher 返回值和一个打开的(可能是解压缩的)文件句柄。
- 解压是在流上完成的,以减少内存需求 避免在handler提前返回时浪费处理。
- 如果recurse参数为true,并且walker遇到 tarfile嵌入到tarfile中,其内容也将 扫描方式相同。
提供了两(2)个类。主要区别 如果给定目录,tarwalker将引发异常。
- tarwalker处理压缩或未压缩的文件,以及tarfile 档案。
- tardirwalker是tarwalker的子类,它将其扩展为 递归地遍历目录,处理任何文件 遇到。
安装
使用pip安装包,例如:
pip install –user tarwalker
pip3 install –user tarwalker
示例
以下是在文件中查找给定字符串的简单工具。 文件可以作为参数或在tarballs中给出,并且必须以 “.log”(带可选数字后缀)或带“.txt”:
importreimportsysfromtarwalkerimportTarWalkerPATTERN=re.compile(r'.*\.(txt|log(\.\d+)?)$')defhandler(fileobj,filename,arch,info,match):try:forlineinfileobj:iftextinline:path=(arch+':')ifarchelse''print("Found in: "+path+filename)returnexceptIOError:passtext=sys.argv[1]walker=TarWalker(file_handler=handler,name_matcher=PATTERN.match,recurse=False)forarginsys.argv[2:]:walker.handle_path(arg)
构造函数和回调
构造tarwalker或tardirwalker的实例 相同的参数。请注意,file_matcher或 name_matcher是允许的。
file_处理程序(必需)一个可调用的,包含五(5)个位置参数:
fileobj - a readable file object for the file contents.
filepath - a str with the filename, either as one of:
- the file path given to handle_path(), or
- the path of a file found beneath a directory given to handle_path().
- the file path of a file within an expanded tar archive.
archname-astr处理 在tar存档中找到的文件。它将是一个冒号(“:”) 如果读取递归tar存档,则使用分隔列表。
fileinfo-可以是none或具有以下内容的对象 属性。有关详细信息,请参见os.stat 详细信息:
- name - the str name of the file,
- size - the size of the file in bytes,
- mtime - modification time, in POSIX (epoch) time,
- mode - the file permission bits,
- uid - the file owner’s User ID, and
- gid - the file owner’s Group ID
match-从name\u matcher或file\u matcher调用返回的值。
注意:带有压缩后缀的文件将具有该后缀 移除,文件对象将返回解压缩的内容。 例如,对于“foo.txt.gz”文件路径将是“foo.txt”和文件对象 相当于“foo.txt”的内容。
file_matcher(可选)接受两(2)个位置的可调用 参数,如果应该打开文件并返回true 传递给文件处理程序回调:
- filepath - See filepath above.
- fileinfo - See fileinfo above.
name_matcher(可选)接受一(1)个位置的可调用 如果文件被打开并传递给 文件处理程序:
- filepath - See file_handler, above.
recurse(可选)如果为true,算法将递归到 在其他地方发现的焦油球柏油球。此外,如果递归是 可调用在打开内部之前和之后调用 皮球,有四(4)个位置参数:
- start - a bool that indicates recursion into the given tarball is starting; it is False on the second call.
- tarname - name of the contained (interior) tarball, see filepath above.
- archive - the name of the containing (exterior) tarball, see archname above.
- fileinfo - See fileinfo above.
已知问题
如果您认为您发现了缺陷,或希望添加增强功能 请求,请通过GitLab issues page:进行。
- 传递给file_handler回调的archname使用“:”作为 分隔符,这是合法的文件名组件,因此 必须指示嵌套存档。
- recurse功能将扫描嵌入的tarfile,但是 目前没有机制可以避免扫描 嵌入tarfile(在任何级别)。如果需要,请提交 增强请求。
- 还有很多其他的压缩算法没有被处理。