Copy-paste into Python interactive interpreter and indentation

懵懂的女人 提交于 2019-11-27 04:33:21

问题


This piece of code, test.py:

if 1:
   print "foo"
print "bar"

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

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

Why is it so? Can interpreter by configured in such a way that it would read copy-pasted text succesfully? I guess that may affect typing in the interpreter, but that's ok for me.


回答1:


Indentation is probably lost or broken.

Have a look at IPython -- it's 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:

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 "just works" in the new ipython qtconsole:




回答2:


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 



回答3:


Do %autoindent to Automatic indentation OFF. after that you can past your code in IPython.




回答4:


Continuation lines are needed when entering a multi-line construct. --Interactive mode, The Python Tutorial (v2) (v3)

So you need to enter:

if 1:
   print "foo"

print "bar"

I've yet to find a suitable explanation as to why it's different to a non-interactive session, alas.




回答5:


One other solution I recently found for similar problem:

$ python << EOF
if 1:
   print "foo"
print "bar"

EOF



回答6:


All of the current answers suggest you change to IPython. For a python-only solution, you can use textwrap to remove leading whitespace from lines.

e.g.

>>> code="""    x='your pasted code'
                y='with common indentation'"""
>>> formatted=textwrap.dedent(code)
>>> exec(formatted)



回答7:


If you are like me and use Notepad++ (to copy and paste from), try to replace tabs by spaces by going to settings>preferences>language and check the replace by spaces.

I had this problem myself for so long and I found out that python.exe recognizes spaces.



来源:https://stackoverflow.com/questions/7712389/copy-paste-into-python-interactive-interpreter-and-indentation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!