Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy-paste into Python interactive interpreter and indentation

Tags:

This piece of code, file test.py,

if 1:    print "foo" print "bar" 

can be successfully executed with execfile("test.py") or python test.py, but when one tries to copy-paste it into a Python interpreter:

File "<stdin>", line 3 print "bar"         ^ SyntaxError: invalid syntax 

Why is it so? Can the interpreter by configured in such a way that it would read copy-pasted text successfully?

I guess that may affect typing in the interpreter, but that's OK for me.

like image 271
pms Avatar asked Oct 10 '11 11:10

pms


People also ask

How do you paste into Python interpreter?

To copy text, just select it and hit Ctrl-C (Command-C on a Mac). If the highlight marking the selection disappears, that's normal and it means it's worked. To paste, use Ctrl-V (Command-V on a Mac).

How do I paste multiple lines of code in Python shell?

using pyscripter.. copy code from anywhere say a function... and then right click in interpreter... choose "paste and execute". and this will work nicely for multiline paste.

How do you copy a line of code in Python?

Copy the Line Put the cursor on any line and hit Enter key. This will copy the line.


2 Answers

Indentation is probably lost or broken.

Have a look at IPython -- it's an enhanced Python interpreter with many convenient features. One of them is a magic function %paste that allows you to paste multiple lines of code.

It also has tab-completion, auto-indentation... and many more. Have a look at their site.


Using %paste in IPython:

Enter image description here

And copy-and-paste stuff is one of the things fixed in the Qt console. Here's using a plain old copy-and-paste of your code block that "just works" in the new IPython qtconsole:

Enter image description here

like image 90
rplnt Avatar answered Nov 07 '22 01:11

rplnt


I don't know any trick for the standard command prompt, but I can suggest you a more advanced interpreter like IPython that has a special syntax for multi-line paste:

In [1]: %cpaste Pasting code; enter '--' alone on the line to stop. :for c in range(3): :    print c : :-- 0 1 2 

Another option is the bpython interpreter that has an automatic paste mode (if you are typing too fast to be an human):

>>> for c in range(3): ...     print c ...  0 1 2 >>>   <C-r> Rewind  <C-s> Save  <F8> Pastebin  <F9> Pager  <F2> Show Source  
like image 26
naufraghi Avatar answered Nov 07 '22 03:11

naufraghi