Python解决方案
尽管shell代码可能更短,但整个过程可以在Python中本地完成。 Python解决方案的关键点是:
使用gzip
模块,读取gzip压缩文件与普通文件一样简单。
要获取源文件列表,请使用glob
模块。 它是按照shell glob功能建模的。
要操作路径,请使用Python的os.path
模块。 它提供了一个与操作系统无关的文件系统接口。
这里是示例代码:
import gzip
import glob
import os.path
source_dir = "/dumps/server1"
dest_dir = "/dedupmount"
for src_name in glob.glob(os.path.join(source_dir, '*.gz')):
base = os.path.basename(src_name)
dest_name = os.path.join(dest_dir, base[:-3])
with gzip.open(src_name, 'rb') as infile:
with open(dest_name, 'wb') as outfile:
for line in infile:
outfile.write(line)
这段代码从remote1服务器读取并写入remote2服务器,除非您需要一个本地副本,否则不需要。
在此代码中,所有解压缩都是由本地计算机上的CPU完成的。
Shell代码
为了比较,这里是等效的Shell代码:
for src in /dumps/server1/*.gz
do
base=${src##*/}
dest="/dedupmount/${base%.gz}"
zcat "$src" >"$dest"
done
Python 三步代码
这种稍微复杂一些的方法实现了原帖中的三步算法,该算法使用本地机器上的临时文件:
import gzip
import glob
import os.path
import shutil
source_dir = "./dumps/server1"
dest_dir = "./dedupmount"
tmpfile = "/tmp/delete.me"
for src_name in glob.glob(os.path.join(source_dir, '*.gz')):
base = os.path.basename(src_name)
dest_name = os.path.join(dest_dir, base[:-3])
shutil.copyfile(src_name, tmpfile)
with gzip.open(tmpfile, 'rb') as infile:
with open(dest_name, 'wb') as outfile:
for line in infile:
outfile.write(line)
这将把源文件复制到本地机器上的临时文件tmpfile
,然后从那里解压缩到目标文件。每次调用此脚本都会覆盖tmpfile
。
临时文件可能存在安全问题。为避免此问题,请将临时文件放置在一个只能被运行此脚本的用户所写入的目录中。
open(dest_name, 'wb')
,这样它也可以在Python3中工作。 - John1024