I would like to save the input code and the output result into a file. For example the following python code code.py
:
print(2 2)
print(3 2)
to create a code-and-output.txt
:
>>> print(2 2)
4
>>> print(3 2)
5
But I can not get it working. Basically, I want to code-and-output.txt
to capture what would happen if I run interpreted python and run statements in python interactive environment (code output).
Ways that I have tried so far:
Redirect stdout:
python code.py > code-and-output.txt
It only saves the output.
Redirect stdout and stdin:
python < code.py > code-and-output.txt
It does the same (only output).
nohup
nohup python code.py
The same problem: only output.
Script
script -q code-and-output.txt
python
print(2 2)
print(2 3)
ctr d
ctr d
It works but I need to do it manually. Moreover, it saves some garbage that I can not make them quiet with -q.
Bash Script
# bash-file.sh
python &
print(2 2)
print(2 3)
Does not work: commands run in console bash, not python. It does not work with &
either: never ends python repl.
Using tty
open another terminal like /dev/pts/2
and send above bash-file.sh
cat bash-file.sh > /dev/pts/2
It just copies but does not run.
I am not interested in solutions like Jupyter and iPython. They have their own problems that does not address my requirement.
Any solution through linux commands (preferably) or python? Thank you.
CodePudding user response:
Save this is as repl_sim.py
in the same directory as your code.py
:
with open("code.py", 'r') as input_file:
for line in input_file:
print(f">>> {line.strip()}")
eval(line)
Then run in your terminal with the following if you want to redirect the output to a text file named code-and-output.txt
:
python repl_sim.py > code-and-output.txt
-OR-
Then run in your terminal with the following if you want to see the output as well as the make the text file matching:
python repl_sim.py | tee code-and-output.txt
It at least works for the example you provided as code.py
.
Pure Python version of first option above so that you don't need shell redirect.
Save this code as repl_sim.py
:
import contextlib
with open('code-and-output.txt', 'w') as f:
with contextlib.redirect_stdout(f):
with open("code.py", 'r') as input_file:
for line in input_file:
print(f">>> {line.strip()}")
eval(line)
Then run in your terminal with:
python repl_sim.py
That will result in code-and-output.txt
with your desired content.
Contextlib use based on Raymond Hettinger's August 17th 2018 Tweet and contextlib.redirect_stdout() documentation .