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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With