Amelio Vazquez-Reina
Amelio Vazquez-Reina

Reputation: 96264

Redirecting-output and/ saving contents of a variable in ASCII to disk in IPython

I would like to be able to do the following during an IPython session:

  1. Easily save the contents of a variable to disk in an ASCII file
  2. Easily re-direct stdout to disk for a given command

by easily I mean for example by using a magic (i.e. I would like to avoid having to type multi-line statements in IPython, opening file descriptors, etc.).

This answer in this thread suggests using

%edit some_variable

to open the value of a variable in the editor (based on the value of $EDITOR) from which I could later save things to disk. This sounds great but when I try it on a regular Python variable

> my_variable = 'Hello world'
> %edit a

I get TypeError: 'NoneType'object is not iterable (By the way, I know that my $EDITOR env. variable works well, since other programs I use rely on it. either way $EDITOR is emacsclient in my case)

I have also tried with:

%save 'test.txt' print(my_variable)

with the hope that it would re-direct the output of the statement print(my_variable) to test.txt, but instead I get the following error:

'print(a)' was not found in history, as a file, url, nor in the user namespace.

Any thoughts on how to accomplish this?

Upvotes: 1

Views: 975

Answers (2)

john1king
john1king

Reputation: 21

You can save a variable to file by %store foo > foo.txt, and capture stdout/stderr by %%capture magic, maybe helpful.

Upvotes: 2

Matt
Matt

Reputation: 27843

IPython dev have a %%writefile magic that dumps raw content of cell on disk. Would it help ? Otherwise you will have to write your own magic (not too difficult)

Upvotes: 1

Related Questions