37

Is there a way to paste a block of code into IDLE? Pasting line by line works, but sometimes I'd like to paste many lines at once. When I try, IDLE reads the first line and ignores the rest.

>>> a = 1
b = 2
c = 3

>>> 
>>> a
1
>>> b

Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    b
NameError: name 'b' is not defined
foosion
  • 7,619
  • 25
  • 65
  • 102

4 Answers4

60

Probably not the most beautiful procedure, but this works:

cmds = '''

paste your commands, followed by ''':

a = 1
b = 2
c = 3
'''

Then exec(cmds) will execute them.

Or more directly,

exec('''

then paste your commands, followed by '''):

a = 1
b = 2
c = 3
''')

It's just a trick, maybe there's a more official, elegant way.

RedGlyph
  • 11,309
  • 6
  • 37
  • 49
  • 1
    that works, but I was really hoping for something more elegant. It's pretty common to paste a bunch of lines into IDLE. Testing parts of code from an IDE or running stuff posted on SO or whatever. – foosion Oct 23 '09 at 20:01
  • 3
    Yes, I often ran into the same issue and asked myself the same question... Same happens when pasting indented part of code, "solved" by typing `if True:` then pasting the code. A bit of a dirty trick ;-) – RedGlyph Oct 23 '09 at 20:10
  • 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. – ihightower Jan 19 '17 at 11:27
  • Nice trick! To get rid of copied indentation one can use stdlib `textwrap.dedent(exec(cmds))`. – antonagestam Apr 08 '21 at 07:47
8

IdleX provides the PastePyShell.py extension for IDLE which allows pasting of multiple lines into the shell for execution.

Roger
  • 951
  • 8
  • 6
3

See this other post: Python, writing multi line code in IDLE You can use an editor (File > New File), write your lines of code there and use F5

aless80
  • 3,122
  • 3
  • 34
  • 53
0

Based on the answer of RedGlyph, but with some automation using AutoHotKey:

; python Idle shell
#IfWinActive ahk_exe pythonw.exe

^+x::  ; Idle - multiple commands paste 
SoundBeep,1700, 150
send, ^{end}
var1 = cmds = '''
var2 := clipboard
var3 = %var1%%var2%
var4 = %var3%'''
msgbox,,, %var4%,2
clipboard = %var4%
send, ^{vk0x56}   ;send, ^v
send, {enter}
sleep, 1000
send, exec(cmds)
return

You need to install AutoHotKey to make this work. After Installing AutoHotKey, the above code sample must be saved in a file with extension AHK (e.g. Idle.ahk), and should be running always to enable the shortcut: Ctrl+Shift+x to make the string manipulation for you.

yosi
  • 18
  • 5