Search code examples
pythonsqlpandassqlalchemystdout

How to save stdout instead of printing directly on console?


When I call some third party library and there may be some stdout from it. For example pd.read_sql, and there may be output like

2022-08-01 17:15:47,216 INFO sqlalchemy.engine.Engine SHOW VARIABLES LIKE 'sql_mode'

2022-08-01 17:15:47,217 INFO sqlalchemy.engine.Engine [raw sql] ()

2022-08-01 17:15:47,260 INFO sqlalchemy.engine.Engine SHOW VARIABLES LIKE 'lower_case_table_names'

2022-08-01 17:15:47,260 INFO sqlalchemy.engine.Engine [generated in 0.00024s] ()

2022-08-01 17:15:47,346 INFO sqlalchemy.engine.Engine SELECT DATABASE()

2022-08-01 17:15:47,346 INFO sqlalchemy.engine.Engine [raw sql] ()

2022-08-01 17:15:47,476 INFO sqlalchemy.engine.Engine SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = %s AND table_name = %s

2022-08-01 17:15:47,476 INFO sqlalchemy.engine.Engine [generated in 0.00027s] ('test', 'select * from A')

2022-08-01 17:15:47,520 INFO sqlalchemy.engine.Engine select * from A

2022-08-01 17:15:47,520 INFO sqlalchemy.engine.Engine [raw sql] ()

But I really don't want them to print directly onto console, instead I want to save them temporarily and use them when I want.

Is there a way to achieve what I want?


Solution

  • How to save stdout instead of printing directly on console?

    This looks like task for contextlib.redirect_stdout, simple usage example

    import contextlib
    import io
    def printing_func():
        print("Hello World")
    with contextlib.redirect_stdout(io.StringIO()) as f:
        printing_func()
    s = f.getvalue()
    print(s)
    

    output

    Hello World