问题
I try to redirect the output of my script to a file. I don't want to do something like
python myscript.py > xy.out
as a lot of the variable is being stored in my ipython environment and I like to carry it over.
I try to follow this link
IPython: redirecting output of a Python script to a file (like bash >)
however, when I try to do
with redirect_output("my_output.txt"):
%run my_script.py
It gives the error
---> 10 self.sys_stdout = sys.stdout
NameError: global name 'sys' is not defined
There is a similar solution to copy the output of a ipython shell to a file but It says my cell its not defined
https://www.quora.com/How-do-I-export-the-output-of-the-IPython-command-to-a-text-file-or-a-CSV-file
Is there a easier way or build in feature with ipython that does that ?? e.g.
In oracle sqlplus there is a spool command e.g.
spool /tmp/abc
select * from table_x;
spool off
now the sql statement output is in /tmp/abc
Is such a equivalent for ipython ??
回答1:
Greeting. I end up using this solution:
%%capture var2
%run -I script2
import sys
orig_stdout = sys.stdout
f = file('out5.txt', 'w')
sys.stdout = f
print var2
stdout = orig_stdout
f.close()
It is not very handy but it works!
来源:https://stackoverflow.com/questions/40029938/redirect-output-of-ipython-script-into-a-csv-or-text-file-like-sqlplus-spool