halloleo
halloleo

Reputation: 10374

How to execute some arbitary Python code in InteractiveConsole before jumping into interact

In a Python application I want to open a Python REPL via the InteractiveConsole class. But before I jump into the interactive Python prompt (via the interact method) I want to execute some commands given as strings. Here a Minimal example:

pre_commands = """for i in range(3):
    print(i*i)
for i in range(3):
    print(i*17)
"""

console = code.InteractiveConsole()


for l in pre_commands.splitlines():
    console.push(l)

console.interact(banner="", exitmsg="")

This always errors out with SyntaxError: invalid syntax on the 3rd line of pre_commands. It looks like push understand only one complete command (like

for i in range(3):
    print(i*i)

and not another command, despite the fact that InteractiveConsole.push has a mechanism for waiting until a command is complete.

How can I make this work with arbitrary lines of complex and simple commands in the string pre_commands?

Upvotes: 0

Views: 52

Answers (1)

Sumit
Sumit

Reputation: 1525

Looks like interactive means Hit Enter/Return key after each block to execute it.

And Enter/Return key also means new line. Your code works if I add new line after each print like below:

pre_commands = """for i in range(3):
    print(i*i)

for i in range(3):
    print(i*17)

"""

OR, Send each line with a \n, e.g. with the line console.push(l+'\n').

Upvotes: 2

Related Questions