Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

using in interactive mode #4

Open
jeog opened this issue Feb 6, 2016 · 4 comments
Open

using in interactive mode #4

jeog opened this issue Feb 6, 2016 · 4 comments

Comments

@jeog
Copy link

jeog commented Feb 6, 2016

Thanks for this, it's very helpful...

I was wondering if there is a way to run this on a file that you import from an interactive shell(or when using the -i switch)

When I try to import a file that looks like:

from pypreprocessor import pypreprocessor
pypreprocessor.input = __name__ + '.py'
pypreprocessor.parse()

... 

I get the expected behavior, but the sys.exit() after on_the_fly() in post_process() closes the interpreter. I'm not sure if there's a way around that without messing with the python compiler/interpreter or using an exception to breakout of the import process - neither of which seems very appealing.

Or am I just missing something simple?

-jon

@evanplaice
Copy link
Member

@jeog I'm not sure if it could be made to work in interactive mode.

The way it works is. Once the parse() statement is hit, it loads the rest of the file into memory, comments out lines that shouldn't be used depending on the #ifdef statements, then runs the parsed file as code.

@jeog
Copy link
Author

jeog commented Feb 10, 2016

best I could come up with is to wrap the import like so...

def interactive_import(module, obj=pypreprocessor):
    import types, inspect  
    g = inspect.stack()[1][0].f_globals # use previous frame's globals
    def interactive_on_the_fly(self):    
        try:
            m = self.output.split('.')[0]     
            g[module] = __import__(m,globals=g) # import the tmp_... version
        except:
            self.rewrite_traceback()
        finally:
            os.remove(self.output) # remove tmp_... file
    try:
        obj.on_the_fly = types.MethodType(interactive_on_the_fly, obj)  # 'override' on_the_fly method  
        __import__(module)     
    except SystemExit: # catch sys.exit, return control to interactive shell
        pass

@evanplaice
Copy link
Member

Well, you could try removing sys.exit(0) on line 201. I didn't consider interactive mode when I wrote the lib but removing that statement shouldn't hurt anything as the code defaults to eventually return a success code if nothing fails.

@Epikem
Copy link
Contributor

Epikem commented Feb 5, 2018

On current version you could use resume option. #12

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants