5

From an python interactive session, is there a way to enter a REPL loop inside a with statement?

Normally, a with statement is executed as a single block

>>>
>>> with app.app_context():
>>> ...   # Normally this is executed as a single block, all at once

I'd like to be able to run code in an interactive session, in the context.

>>>
>>> with app.app_context():
>>> # do stuff here in a REPL loop
00500005
  • 3,727
  • 3
  • 31
  • 38

2 Answers2

7

You can't exactly mimic a with statement, but you can probably get close by calling app.app_context().__enter__() manually.

This won't __exit__ automatically if there's an exception, but otherwise it should work the same (you might need to call __exit__ yourself when you're done, I'm not sure what exactly that context manager does).

Blckknght
  • 100,903
  • 11
  • 120
  • 169
  • A context manager calls `__exit__` for any exit condition, and can do things like recover or change exceptions. But for my purposes, that's not that useful – 00500005 Apr 08 '16 at 22:38
  • Yeah, that's why I mentioned calling `__exit__` yourself. It might not matter though, depending on what the `app_context` context manager does (its `__exit__` method may do little or nothing). – Blckknght Apr 08 '16 at 22:44
0

A fully-functioning REPL for very simple inputs (i.e. no variable declarations) with a contextmanager in Python 2.7:

from contextlib import contextmanager
import sys 
class app(object):
    @contextmanager
    def app_context(self):
       sys.stdout.write(">>> ")
       yield raw_input()

with app().app_context() as output:
   while True:
       print eval(output)
       output = app().app_context().__enter__()

This will need some work to handle anything more sophisticated - that eval is an eyesore, and there's no good way to break the loop short of ^C - but it should work.

Akshat Mahajan
  • 9,543
  • 4
  • 35
  • 44