Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IPython: redirecting output of a Python script to a file (like bash >)

Tags:

python

io

ipython

I have a Python script that I want to run in IPython. I want to redirect (write) the output to a file, similar to:

python my_script.py > my_output.txt 

How do I do this when I run the script in IPython, i.e. like execfile('my_script.py')

There is an older page describing a function that could be written to do this, but I believe that there is now a built-in way to do this that I just can't find.

like image 857
wwwilliam Avatar asked Jan 28 '13 20:01

wwwilliam


People also ask

What does %% Writefile do in Python?

%%writefile lets you output code developed in a Notebook to a Python module. The sys library connects a Python program to the system it is running on. The list sys. argv contains the command-line arguments that a program was run with.

Which is the command to run the script in Ipython?

You can use run command in the input prompt to run a Python script. The run command is actually line magic command and should actually be written as %run. However, the %automagic mode is always on by default, so you can omit this.


1 Answers

IPython has its own context manager for capturing stdout/err, but it doesn't redirect to files, it redirects to an object:

from IPython.utils import io with io.capture_output() as captured:     %run my_script.py  print captured.stdout # prints stdout from your script 

And this functionality is exposed in a %%capture cell-magic, as illustrated in the Cell Magics example notebook.

It's a simple context manager, so you can write your own version that would redirect to files:

class redirect_output(object):     """context manager for reditrecting stdout/err to files"""       def __init__(self, stdout='', stderr=''):         self.stdout = stdout         self.stderr = stderr      def __enter__(self):         self.sys_stdout = sys.stdout         self.sys_stderr = sys.stderr          if self.stdout:             sys.stdout = open(self.stdout, 'w')         if self.stderr:             if self.stderr == self.stdout:                 sys.stderr = sys.stdout             else:                 sys.stderr = open(self.stderr, 'w')      def __exit__(self, exc_type, exc_value, traceback):         sys.stdout = self.sys_stdout         sys.stderr = self.sys_stderr 

which you would invoke with:

with redirect_output("my_output.txt"):     %run my_script.py 
like image 121
minrk Avatar answered Sep 24 '22 02:09

minrk