I was wondering if there was away to redirect both the input and output of a python script to a file so that they were interlaced. Essentially say I have the following code:
x = 1 print("hello, world") print(x) x = 2 print(x) def myfun(Val): return(Val+1) myfun(7) I would be looking for the following to be displayed in an output file
x = 1 print("hello, world") "hello, world" print(x) 1 x = 2 print(x) 2 def myfun(Val): return(Val+1) myfun(7) 8 Things that I have already looked at include:
simple file redirecting
python myfile.py > output.loghowever this doesn't capture the inputThe trace module
python -m trace myfile.pyhowever this displays way way way too much information and bloats the runtime. I couldn't find any obvious way of limiting this to just the top level code (not every module and function call)Jupyter notebooks - I appreciate that these clearly display input and output however I really want to keep this to command line executable scripts with basic ascii python files.
Ideally I was hoping to find either some sort of bash wizardry with re-directs, a python command line option or a common python module that is able to handle this, but so far no luck :(
EDIT: As a further clarifying example essentially I am trying to re-create the following functionality from R. Say we have the R program myprog.R as:
myfun <- function(x){ x + 1 } y <- myfun(7) print("hello,world!") print(y) y + 1 Then running from the command line R CMD BATCH myprog.R produces the file myprog.Rout which looks like
myfun <- function(x){ x + 1 } y <- myfun(7) print("hello,world!") [1] "hello,world!" print(y) [1] 8 y + 1 [1] 9
>>>but IMHO that clearer, anyway.