代码之家  ›  专栏  ›  技术社区  ›  equallyhero

TypeError:应为str、bytes或os。类路径对象,而不是io。拜特西奥

  •  4
  • equallyhero  · 技术社区  · 8 年前

    正在尝试使用ssh将文件从internet上载到我的服务器。有下面的代码可以上传本地文件,但我不知道要上传图片字节对象还需要做什么。

    from io import BytesIO
    import requests
    import pysftp
    url = 'https://vignette.wikia.nocookie.net/disney/images/d/db/Donald_Duck_Iconic.png'
    
    cnopts = pysftp.CnOpts()
    cnopts.hostkeys = None 
    response = requests.get(url)
    netimage = BytesIO(response.content) #imagefromurl
    
    srv = pysftp.Connection(host="12.34.567.89", username="root123",
    password="password123",cnopts=cnopts)
    
    with srv.cd('/var/www'): #srvdir
        #srv.put('C:\Program Files\Python36\LICENSE.txt') #local file test
        srv.put(netimage) 
    
    print('Complete')
    
    1 回复  |  直到 8 年前
        1
  •  5
  •   Martijn Pieters    8 年前

    您需要使用 .open() method 要获取类似文件的对象,然后跨数据进行复制,请使用 shutil.copyfileobj() :

    import shutil
    
    with srv.cd('/var/www'):
        with srv.open(image_filename, 'w') as remote_file:
            shutil.copyfileobj(netimage, remote_file)
    

    Paramiko(扩展名为pysftp)不支持直接放入内存中的文件对象。

    推荐文章