复制粘贴到Python交互式解释器和缩进中 [英] Copy-paste into Python interactive interpreter and indentation

查看:253
本文介绍了复制粘贴到Python交互式解释器和缩进中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这段代码,文件 test.py

if 1:
   print "foo"
print "bar"

可以用<$ c成功执行$ c> execfile( test.py)或 python test.py ,但是当有人尝试将其复制粘贴到Python解释器中时:

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.

推荐答案

缩进可能丢失或损坏。

看看在 IPython 中-它是增强的Python解释器,具有许多便利的功能。其中之一是魔术函数%paste ,它允许您粘贴多行代码。

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.

使用%paste IPython:

Using %paste in IPython:

复制粘贴是Qt控制台中解决的问题之一。这是在新的 IPython qtconsole 中使用普通的代码块的复制粘贴:

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:

这篇关于复制粘贴到Python交互式解释器和缩进中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆