Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Piping commands into the Python REPL

I have a file containing Python statements, and I'd like to run Python in such a way that it prints to stdout what would be shown if those commands were run in the REPL.

For example, if the file is

1 + 4
'a' + 'b'

Then the output should be

>>> 1 + 4
5
>>> 'a' + 'b'
'ab'

Is there a way to do this?

like image 518
Chris Martin Avatar asked Dec 12 '22 03:12

Chris Martin


1 Answers

You can use replwrap from pexpect to achieve this goal, even has a python method:

from pexpect import replwrap

with open("commands.txt", "r") as f:
    commands = [command.strip() for command in f.readlines()]

repl = replwrap.python()
for command in commands:
   print ">>>", command
   print repl.run_command(command),

Which returns:

python replgo.py 
>>> 1 + 4
5
>>> 'a' + 'b'
'ab'

You'll need to get the latest version of pexpect.

like image 153
Noelkd Avatar answered Jan 05 '23 01:01

Noelkd