简体   繁体   English

Python访问嵌套函数内的父变量

[英]Python accessing parent variable inside nested function

def download(self):
    ftp = self.connect()
    try:
        size = ftp.size(filename=self.filename)
        print "Total size of {filename} is {size}".format(filename=self.filename, size=size)
        written_till_now = 0
        def handle(bytes):
            f.write(bytes)
            print "written bytes: {}".format(bytes)

        with open(self.filename, 'wb') as f:
            ftp.retrbinary('RETR {}'.format(self.filename), handle)
    except (socket.error, error_perm) as e:
        raise DownloaderException("Error in downloading file {filename}: {message}".format(filename=self.filename, message=str(e)))
    except EOFError as e:
        print "file {filename} downloaded successfully".format(filename=self.filename)

I want to keep track of the amount of data i've currently downloaded and later do some additional stuff also for every stream of data i download. 我想跟踪当前下载的数据量,以后再对我下载的每个数据流做一些额外的事情。

I created a handle function inside the download function. 我在download功能内创建了一个handle功能。

Python ftblip.retrbinary provides the data to the given callback. Python ftblip.retrbinary将数据提供给给定的回调。 In my case handle but somehow it is not executing. 在我的情况下handle但不知何故它没有执行。

Also I doubt i am not understanding the scope of variables when it comes to nested functions. 我也怀疑我是否不了解嵌套函数的变量范围。 In my understanding I can use variable defined in parent scope in the child scope as long as i am not modifying them.But in this case f is a object and i am not modifying it rather calling its method write . 以我的理解,只要不修改它们,我就可以在父作用域中使用在父作用域中定义的变量。但是在这种情况下, f是一个对象,我不对其进行修改,而是调用其方法write Please correct me if i am missing something. 如果我缺少某些东西,请纠正我。

The handle function doesn't have access to the scoped f variable. handle函数无权访问作用域f变量。 Instead you can pass the open file directly to handle . 相反,您可以直接将打开的文件传递给handle

def handle(fp, bytes):
    fp.write(bytes)
    print "written bytes: {}".format(bytes)

with open(self.filename, 'wb') as f:
    ftp.retrbinary('RETR {}'.format(self.filename), lambda b: handle(f, b))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM