English 中文(简体)
情况管理者是否有权得到这一工作?
原标题:Is a context manager right for this job?

如下文所述守则:

  • creates an import hook
  • creates a context manager which sets the meta_path and cleans on exit.
  • dumps all the imports done by a program passed in input in imports.log

现在,我很想知道,在这种情况下,是否使用环境主管是一个好的想法,因为实际上,我没有标准<条码>/最终的流通,而只是设置和清理。

另一回事——此行:

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

None? 是否应当成为<条码>。

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 =  
 .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()
最佳回答

既然每个人都能顺利工作,我实际上想回去,因为我想把“跑”放在背景经理内部,所以我会说几句话。

此外,现在,我储存了老的雕像,并在撤离时恢复,也许不是根本性的,而是我认为要做的事情。

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.old_argv = argv[:]
        self.output_file = output_file
        self.progname = self.old_argv[1]

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

    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)
        sys.argv = self.old_argv[:]

    def run(self):
        code = compile(open(self.progname).read(), self.progname,  exec )
        exec(code)


def main_context():
    cl = CollectImports()

    with CollectorContext(cl, sys.argv,  imports.log ) as cc:
        cc.run()
问题回答

我认为这一概念已经过时。 同样,我看不出任何理由反对将清理放在<条码>中:条款中,因此背景主管完全适合。

Your cc is None, because you told it to be so.

如果您不希望的话,将 enter__ 返回的方法:

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)

如果你总是想进行清理,那么你就应当使用一名环境管理员。 如果你使用低级特殊方法执行环境主管,我不肯定你使用<代码>try.finally。 如果你使用@contextmanager decorator,请以“自然”的方式对背景管理人进行编码,以便你在什么地方使用try.finally,而不是将例外作为参数。

另外,<条码>cc>是您从<条码>>(<>>>> > > /代码>返回的价值。 页: 1 我理解环境主管设计的方式是,回报价值是“文字”。 情况主管机构做了些什么,并清理了发生其他事情的背景。 例如,数据库连接将产生交易,数据库业务在交易范围内进行。

That said, the above is just there to provide maximum flexibility. There s nothing wrong with just creating a context (that manages itself) directly and returning self, or even not returning anything if you don t need to use the context value inside the with. Since you don t use cc anywhere, you could just do and not worry about the return value:

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




相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签