python的交互式解释器,复制粘贴到Python交互式解释器和缩进中

本文讨论了在Python环境中,直接复制粘贴代码到解释器可能导致的缩进错误,以及如何通过使用IPython的%paste功能解决这个问题。IPython是一个增强型的Python交互式 shell,提供多行输入、自动补全和代码高亮等功能,对于开发者来说更加便捷。
摘要由CSDN通过智能技术生成

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 "", 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.

解决方案

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:

o3cUg.png

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:

Zh6mG.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值