How to check python code containing blank lines in interpreter

The python interpreter seems to decide "it's time to run my code" when it sees a newline. Is there a workaround for this?

the scala equivalent is to run ": paste" on a code snippet.

By the way, we have environment limitations, so we intend to use strictly the python interpreter (2.6.X) and not something "nicer" like ipython or another version of python.

+3


source to share


1 answer


As a workaround, you can open block

, for example, a block try

- except

or a block if

:

>>> if True:
...  #my statements
...  #which I don't want to execute right now
...  pass # or do_stuff()
... 

      

or wrap your snipplet in a function and then call it.

The obvious solution would be to use an interpreter shell that supports insertion, like ipython

(has %paste

and %cpaste

), but unfortunately this is not an option for you; the default python shell doesn't have a similar mechanism AFAIK.



Another workaround would be to store the snipplet in a tempfile and call it execfile(filename)

, or perhaps use it exec(<pastedcode>)

for small snipplets.

Actually concatenation exec

, abuse of multi-line strings as heredocs and implicit _

might be the best workaround, seems pretty handy:

>>> """
... x = 5
... y = x**2
... print(x,y)
... """
'\nx = 5\ny = x**2\nprint(x,y)\n'
>>> exec(_)
5 25
>>> x, y # above code was executed in current scope, see?
(5, 25)

      

0


source







All Articles