pypreprocessor icon indicating copy to clipboard operation
pypreprocessor copied to clipboard

using in interactive mode

Open jeog opened this issue 9 years ago • 4 comments
trafficstars

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

jeog avatar Feb 06 '16 18:02 jeog

@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.

evanplaice avatar Feb 06 '16 20:02 evanplaice

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

jeog avatar Feb 10 '16 00:02 jeog

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.

evanplaice avatar Apr 11 '17 23:04 evanplaice

On current version you could use resume option. #12

Epikem avatar Feb 05 '18 00:02 Epikem