将IPython脚本的输出重定向到类似于sqlplus sp的CSV或文本文件中

2024-06-15 18:39:45 发布

您现在位置:Python中文网/ 问答频道 /正文

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

python myscript.py > xy.out

因为很多变量都存储在我的ipython环境中,我喜欢把它带过去。在

我试着跟踪这个链接

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

但是,当我试着

^{pr2}$

它给出了错误

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

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

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

ipython是否有一种更简单的方法或内置特性来实现这一点?? e、 g

在oraclesqlplus中有一个spool命令 e、 g

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

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

这对ipython来说是等价物吗??在


Tags: 文件oftheto脚本outputipythonstdout
2条回答

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

%%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()

这不是很方便,但它很管用!在

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)
^{pr2}$

相关问题 更多 >