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

后端 未结 7 2080
慢半拍i
慢半拍i 2020-12-01 03:50

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
         


        
7条回答
  •  -上瘾入骨i
    2020-12-01 04:03

    While this an old question, I found this and the answers as I was facing a similar problem.

    The solution I found after sifting through IPython Cell magics documentation is actually fairly simple. At the most basic the solution is to assign the output of the command to a variable.

    This simple two-cell example shows how to do that. In the first Notebook cell we define the Python script with some output to stdout making use of the %%writefile cell magic.

    %%writefile output.py
    print("This is the output that is supposed to go to a file")
    

    Then we run that script like it was run from a shell using the ! operator.

    output = !python output.py
    print(output)
    >>> ['This is the output that is supposed to go to a file']
    

    Then you can easily make use of the %store magic to persist the output.

    %store output > output.log
    

    Notice however that the output of the command is persisted as a list of lines. You might want to call "\n".join(output) prior storing the output.

提交回复
热议问题