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

后端 未结 7 2084
慢半拍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条回答
  •  北海茫月
    2020-12-01 04:10

    use this code to save the output to file

    import time
    from threading import Thread
    import sys
    #write the stdout to file
    def log():
        #for stop the thread
        global run
        while (run):
            try:
                global out
                text = str(sys.stdout.getvalue())
                with open("out.txt", 'w') as f:
                    f.write(text)
            finally:
                time.sleep(1)
    
    %%capture out
    run = True
    print("start")
    process = Thread(target=log, args=[]).start()
    
    # do some work
    for i in range(10, 1000):
        print(i)
        time.sleep(1)
    run= False
    process.join()
    

    It is useful to use a text editor that tracer changes the file and suggest reloading the file like notepad++

提交回复
热议问题