Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6865995
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 27, 20262026-05-27T03:07:30+00:00 2026-05-27T03:07:30+00:00

The code pasted below does the following: creates an import hook creates a context

  • 0

The code pasted below does the following:

  • 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

Now I was wondering if using a context manager is a good idea in this case, because actually I don’t have the standard try/finally flow, but just a set up and clean up.

Another thing — with this line:

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

does cc become None? Shouldn’t it be a CollectorContext object?

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()
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-27T03:07:31+00:00Added an answer on May 27, 2026 at 3:07 am

    Thanks everyone now it works smoothly, I actually wanted with to return something because I wanted to encapsulate the “run” inside the context manager, so I get something as below.

    Moreover, now I store the old sys.argv and restore it on exit, probably not fundamental but still a nice thing to do I think..

    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()
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have the following code pasted below. For some reason, the response.redirect seems to
I have a plot (sample code pasted below) that I am trying to add
Firstly sorry for the long piece of code pasted below. This is my first
The code I have pasted below is meant to display images on the middle
In the code base I was maintaining I found this exact class, pasted below.
I am trying to read a text file using the code (pasted below), but
I have a code file from the boto framework pasted below, all of the
I pasted the code given in this link to a file called md5.js. http://www.webtoolkit.info/javascript-md5.html
For a rich text editor that has to handle pasted HTML code from MS
Pasted a piece of code from the shell script transfer.sh if [[ ${ld} -eq

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.