【问题标题】:ftplib callbacks not working - Python 3ftplib 回调不起作用 - Python 3
【发布时间】:2012-01-07 00:40:35
【问题描述】:

我到处找,找不到解决这个问题的方法,ftplib storbinary 回调。 这是我第一次使用回调,所以它可能很愚蠢,我假设每次上传 8192 字节时我都有一些代码应该调用我的函数(这就是我认为回调在研究后的工作方式)。

#In main thread
def ftpcallback(intid):
    ftpuploaded = transStatus[intid][3] + 8192 #transStatus[intid] equals 0 to start with
    if ftpuploaded > transStatus[intid][2]: ftpuploaded = transStatus[intid][2] #Is this needed? It's supposed to just keep the value below the file size
    transStatus[intid][3] = ftpuploaded
    print (transStatus[intid][3]) #Always outputs 8192
    print("Callback called")

#Not in main thread
#FTP and file open code

self.ftp.storbinary("STOR " + self.destname, self.f, 1, ftpcallback(self.intid)) #1 to (hopefully) spam the output more

#close FTP and file code

无论何时运行,回调只运行一次,即使是 10MB 的文件。我究竟做错了什么? 提前致谢

【问题讨论】:

    标签: python upload ftp callback ftplib


    【解决方案1】:

    回调,顾名思义,就是当您告诉一段代码 (ftplib) 给您回电时。您所做的是自己调用ftpcallback 函数并将其返回值(即None,因为它没有return 任何内容)传递给storbinary 方法。

    相反,您只想在调用storbinary 时传递函数对象,让ftplib 为您调用该函数。你不想自己称呼它。因此,您需要摆脱(...)

    intid = self.intid
    def ftpcallback():
        ftpuploaded = transStatus[intid][3] + 8192  # transStatus[intid] equals 0 to start with
        if ftpuploaded > transStatus[intid][2]:
            ftpuploaded = transStatus[intid][2]  # Is this needed? It's supposed to just keep the value below the file size
        transStatus[intid][3] = ftpuploaded
        print(transStatus[intid][3])  # Always outputs 8192
        print("Callback called")
    
    #FTP and file open code
    
    self.ftp.storbinary("STOR " + self.destname, self.f, 1, ftpcallback)
    

    ftplib 文档没有说明回调参数,所以我假设它在调用回调时没有将任何参数传递给回调。因此,您的 ftpcallback 必须可以作为 ftpcallback() 调用,即不带参数。这就是我删除intid 参数并在函数前添加intid = self.intid 的原因。

    另一种方法是将ftpcallback 定义为类的方法(def ftpcallback(self):),并将self.ftpcallback 传递给storbinary 调用。然后你可以简单地在方法中使用self.intid

    【讨论】:

    • 哦是的 - 没想到!抱歉,我忘了补充,FTP 连接在一个单独的线程中,而回调函数在主线程中,所以传递变量有点棘手。最好将定义的函数放在另一个线程中,这样它就可以工作,还是将函数保留在主线程中,这样每次运行另一个线程时都不会定义它(很多)?
    • 回调将在调用storbinary的同一线程中运行,即使您在另一个线程中定义了回调函数。定义一个函数相当快,因为​​整个函数体只由 Python 编译一次,但将其作为一个方法对我来说似乎是最干净的方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多