如下文所述守则:
- 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:
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()