如何使用fabri获取没有本地临时文件的远程文件的内容

2024-05-18 14:29:44 发布

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

我想用fabric获取远程文件的内容,而不需要创建临时文件。


Tags: 文件内容远程fabric
3条回答
from StringIO import StringIO
from fabric.api import get

fd = StringIO()
get(remote_path, fd)
content=fd.getvalue()
import tempfile
from fabric.api import get
with tempfile.TemporaryFile() as fd:
    get(remote_path, fd)
    fd.seek(0)
    content=fd.read()

见:http://docs.python.org/2/library/tempfile.html#tempfile.TemporaryFile

和:http://docs.fabfile.org/en/latest/api/core/operations.html#fabric.operations.get

使用Python 3(和fabric3)时,我在使用io.StringIOstring argument expected, got 'bytes'时遇到这个致命错误,显然是因为Paramiko用字节写入类似文件的对象。所以我改为使用io.BytesIO,它工作了:

from io import BytesIO

def _read_file(file_path, encoding='utf-8'):
    io_obj = BytesIO()
    get(file_path, io_obj)
    return io_obj.getvalue().decode(encoding)

相关问题 更多 >

    热门问题