【问题标题】:redirect output of ipython script into a csv or text file like sqlplus spool将 ipython 脚本的输出重定向到 csv 或文本文件,如 sqlplus spool
【发布时间】:2016-10-13 20:02:20
【问题描述】:

我尝试将脚本的输出重定向到一个文件。 我不想做类似的事情

python myscript.py > xy.out

因为很多变量都存储在我的 ipython 环境中,我喜欢将其保留。

我尝试点击这个链接

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

但是,当我尝试这样做时

with redirect_output("my_output.txt"):
    %run my_script.py

它给出了错误

---> 10         self.sys_stdout = sys.stdout
NameError: global name 'sys' is not defined

有一个类似的解决方案可以将 ipython shell 的输出复制到文件中,但它说我的单元格没有定义

https://www.quora.com/How-do-I-export-the-output-of-the-IPython-command-to-a-text-file-or-a-CSV-file

有没有更简单的方法或 ipython 内置功能可以做到这一点? 例如

在 oracle sqlplus 中有一个 spool 命令 例如

spool /tmp/abc
select * from table_x;
spool off

现在sql语句输出在/tmp/abc

ipython 有这样的等价物吗??

【问题讨论】:

  • 在尝试redirect_output 功能之前,您是否import sys

标签: python ipython


【解决方案1】:

问候。我最终使用了这个解决方案:

%%capture var2
%run -I script2

import sys
orig_stdout = sys.stdout
f = file('out5.txt', 'w')
sys.stdout = f 
print var2
stdout = orig_stdout
f.close()

虽然不是很方便,但是很管用!

【讨论】:

  • 据我了解,这将等到您的代码结束,然后将其转储到文件中。那是你所期待的吗? redirect_output函数的优点,据我所见,它会在生成输出时写入文件..所以你可以在日志文件中实时看到输出...
【解决方案2】:
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()

【讨论】:

    猜你喜欢
    • 2013-01-12
    • 2019-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-31
    • 2018-01-11
    • 1970-01-01
    相关资源
    最近更新 更多