gpt4 book ai didi

python - 上下文管理器适合这项工作吗?

转载 作者:太空狗 更新时间:2023-10-30 01:03:28 25 4
gpt4 key购买 nike

下面粘贴的代码执行以下操作:

  • 创建一个导入 Hook
  • 创建一个设置 meta_path 并在退出时清理的上下文管理器。
  • 在 imports.log 中转储通过输入传递的程序完成的所有导入

现在我想知道在这种情况下使用上下文管理器是否是个好主意,因为实际上我没有标准的 try/finally 流程,而只是设置和清理。

另一件事——这一行:

with CollectorContext(cl, sys.argv, 'imports.log') as cc:

cc 是否变成了None?它不应该是一个 CollectorContext 对象吗?

from __future__ import with_statement
import os
import sys

class CollectImports(object):
"""
Import hook, adds each import request to the loaded set and dumps
them to file
"""

def __init__(self):
self.loaded = set()

def __str__(self):
return str(self.loaded)

def dump_to_file(self, fname):
"""Dump the loaded set to file
"""
dumped_str = '\n'.join(x for x in self.loaded)
open(fname, 'w').write(dumped_str)

def find_module(self, module_name, package=None):
self.loaded.add(module_name)


class CollectorContext(object):
"""Sets the meta_path hook with the passed import hook when
entering and clean up when exiting
"""

def __init__(self, collector, argv, output_file):
self.collector = collector
self.argv = argv
self.output_file = output_file

def __enter__(self):
self.argv = self.argv[1:]
sys.meta_path.append(self.collector)

def __exit__(self, type, value, traceback):
# TODO: should assert that the variables are None, otherwise
# we are quitting with some exceptions
self.collector.dump_to_file(self.output_file)
sys.meta_path.remove(self.collector)


def main_context():
cl = CollectImports()

with CollectorContext(cl, sys.argv, 'imports.log') as cc:
progname = sys.argv[0]
code = compile(open(progname).read(), progname, 'exec')
exec(code)


if __name__ == '__main__':
sys.argv = sys.argv[1:]
main_context()

最佳答案

我觉得这个概念没问题。同样,我看不出有任何理由反对在 finally: 子句中进行清理,因此上下文管理器非常适合。

你的 ccNone,因为你告诉它如此。

如果你不想那样,改变你的__enter__ method to return something else :

The value returned by this method is bound to the identifier in the as clause of with statements using this context manager.

def __enter__(self):
self.argv = self.argv[1:]
sys.meta_path.append(self.collector)
return self
# or
return self.collector
# or
return "I don't know what to return here"

然后

with CollectorContext(cl, sys.argv, 'imports.log') as cc:
print cc, repr(cc) # there you see what happens.
progname = sys.argv[0]
code = compile(open(progname).read(), progname, 'exec')
exec(code)

关于python - 上下文管理器适合这项工作吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8243451/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com