Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write the output of ipython command in python text file?

Tags:

ipython

I want to capture the output of the following ipython command into a file: commands and outputs areas follows:

`decoder.get_hyp()`  WARNING: "ngram_search.c", line 1000: </s> not found in last frame, using ++NOISE++ instead INFO: ngram_search.c(1046): lattice start node <s>.0 end node ++NOISE++.171 INFO: ps_lattice.c(1225): Normalizer P(O) = alpha(++NOISE++:171:185) = -2003082 INFO: ps_lattice.c(1263): Joint P(O,S) = -2036704 P(S|O) = -33622 Out[7]: ('WELCOME TO MY TALK', '000000000', -36704586) 

I want to capture only the part "wellcome to my talk" into my file.

like image 497
Anislein Avatar asked Nov 02 '12 16:11

Anislein


People also ask

How do you write the output of a function to a text file in Python?

To write to a text file in Python, you follow these steps: First, open the text file for writing (or append) using the open() function. Second, write to the text file using the write() or writelines() method. Third, close the file using the close() method.

How do I create a file in IPython?

You can create a new Python 3 Jupyter Notebook file (. ipynb) by clicking on New and selecting Python 3 . A new notebook will open a new tab in your web browser.


2 Answers

Use the IPython magic function store

%store foo >a.txt # Store (overwrite) value of foo to file a.txt  %store foo >>a.txt # Append value of foo to file a.txt 
like image 170
Joshua Cook Avatar answered Sep 29 '22 09:09

Joshua Cook


Just do as follow:

%save file_name.py _oh[7] 

PS: Some additional useful command:

%save file_name.py _ 

'_' refers to the previous output.

Or you can:

%save file_name.py _oh[i] 

'i' refers to the output history number, you can see output first via:

_oh 
like image 45
Honghe.Wu Avatar answered Sep 29 '22 07:09

Honghe.Wu