Answer a question

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.

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

Logo

学AI,认准AI Studio!GPU算力,限时免费领,邀请好友解锁更多惊喜福利 >>>

更多推荐