うまい寿司が食いたい。

うまい寿司が遠慮なく食べれるようになるまで,進捗とか垂れ流すブログ

pythonで標準出力を取得する。

f = io.StringIO()
with redirect_stdout(f):
    help(pow)
s = f.getvalue()

公式ドキュメント

終わり!

とするのは味気ないのでなぜこんなことを調べたのか補足。

生存時間解析のライブラリの[lifelines] (https://lifelines.readthedocs.io/en/latest/index.html)を使っているたのですが、fittingした結果をprint()で返す仕様になっていました。
jupyter notebookで使う間はこの仕様でも問題なく動作するのですが、streamlitへ出力する場合には、標準出力は具合が悪いです。
例えばlifelineのCox比例ハザードモデルを実行したとします。

from lifelines import CoxPHFitter
from lifelines.datasets import load_rossi

rossi = load_rossi()

cph = CoxPHFitter()
cph.fit(rossi, duration_col='week', event_col='arrest')

cph.print_summary()  

このときの print_summary() 関数はソースコードを見るとprint() 関数で標準出力しています。

なので、 redirect_stdout() を使って、

from io import StringIO
from contextlib import redirect_stdout


f = StringIO()
with redirect_stdout(f):
    cph.print_summary(style='html')

とすれば、htmlで得られるので、あとはstreamlitを使って、

import streamlit as st

st.markdown(f.getvalue(), unsafe_allow_html=True)

として出力できます。streamlitのissueを見ていると、

github.com

というissueもあるようなので、そのうちstreamlit側で解決されるかも。