Pasting multiple lines into IDLE
Asked Answered
C

4

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
Cassiopeia answered 23/10, 2009 at 19:15 Comment(0)
C
63

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.

Caliphate answered 23/10, 2009 at 19:48 Comment(4)
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.Cassiopeia
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 ;-)Caliphate
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.Aksoyn
Nice trick! To get rid of copied indentation one can use stdlib textwrap.dedent(exec(cmds)).Berget
U
9

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

United answered 26/3, 2012 at 7:34 Comment(0)
E
7

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

Epizoic answered 16/6, 2017 at 13:58 Comment(1)
That requires committing it to disk, an extra hassle (extra time, finding an appropriate place, inventing a name, getting rid of it later, etc.)Hassett
G
0

Based on the answer of RedGlyph, but with some automation using AutoHotkey (AHK):

; 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.

Garmon answered 11/9, 2021 at 18:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.