How To Paste Code in Python Interpreter? Hint: Use iPython

IPython-logo

IPython-logo

If you have formatted code block with proper indentation and want to test it by copying and pasting on a python interpretor, you will be frustrated at Python for complaining at you. iPython offers great solutions for copying and pasting the code right from the terminal interpreter.

One useful command in iPython to play with code block is “%cpaste”. To execute a code block, Type “%cpaste” on the iPython interpreter, it will say ” Pasting code; enter ‘–‘ alone on the line to stop.” Basically, then you just paste your code block and in the next new line type “–” or “Ctrl-D” to execute the code blog. For example

In [8]: %cpaste
Pasting code; enter ‘–‘ alone on the line to stop.
:>>> for i in xrange(100):
:>>> print i
:–

The “%cpaste” offers much more to handle python code snippets. For example, one can assign a python code block to a variable by passing the variable as argument to “%cpaste”. For example ,”%cpaste myCodeBlock’, assigns the pasted code to the variable “myCodeBlock”.