我使用 Fabric 将一个 .gz 文件复制到远程计算机。当我尝试读取同一个远程文件时,显示空字节。
下面是我用来从远程机器读取zip文件的python代码。
try:
fabric_connection = Connection(host = host_name, connect_kwargs = {'key_filename' : tmp_id, 'timeout' : 10})
fd = io.BytesIO()
remote_file = '/home/test/' + 'test.txt.gz'
fabric_connection.get(remote_file, fd)
with gzip.GzipFile(mode = 'rb', fileobj = fd) as fin:
content = fin.read()
print(content)
decoded_content = content.decode()
print(decoded_content)
except BaseException as err:
assert not err
finally:
fabric_connection.close()
给出以下 O/P:
b''
我在远程计算机上进行了验证,内容存在于文件中。
有人可以告诉我如何解决这个问题吗?
fabric_connect
写入fd
,将文件指针保留在文件末尾。您需要先倒回到 BytesIO
文件的前面,然后再将其交给 GzipFile
。
try:
fabric_connection = Connection(host = host_name, connect_kwargs = {'key_filename' : tmp_id, 'timeout' : 10})
fd = io.BytesIO()
remote_file = '/home/test/' + 'test.txt.gz'
fabric_connection.get(remote_file, fd)
fd.seek(0)
with gzip.GzipFile(mode = 'rb', fileobj = fd) as fin:
content = fin.read()
print(content)
decoded_content = content.decode()
print(decoded_content)
except BaseException as err:
assert not err
finally:
fabric_connection.close()