如何捕获 ipython shell 的错误输出?

发布于 2024-08-01 22:23:57 字数 221 浏览 11 评论 0原文

我正在编写一个 ipython 宏来处理程序的输出。 问题是,程序有时可以写入 stderr ,所以如果我这样做:


out = !my_program

out 变量将不包含输出。 我认为它将包含退出代码(如果我错了,请纠正我)。

如何捕获 stdout 和 stderr 流?

I'm writing an ipython macro that processes the output of a program. The thing is, the program can sometimes write to stderr , so if I do something like this :


out = !my_program

the out variable will not contain the output. I think it will contain the exit code ( correct me if I'm wrong ).

How can I capture both stdout and stderr streams?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

℉服软 2024-08-08 22:23:57

foo 2>&1 表示将所有输出,包括句柄 2(即 STDERR),从 foo 命令重定向到句柄 1(即 STDOUT)
所以这里 out = !foo 2>&1 也许就足够了。 下面是演示:
Egg.py:IPython

#!/usr/bin/env python
# -*- coding: utf8 -*-
def main():
    print 'hello'
    print 3/0
if __name__ == "__main__":
    main()

0.10

In [5]: out = !egg.py
Traceback (most recent call last):
  File "D:\python\note\egg.py", line 7, in <module>
    main()
  File "D:\python\note\egg.py", line 5, in main
    print 3/0
ZeroDivisionError: integer division or modulo by zero

In [6]: out
Out[6]: SList (.p, .n, .l, .s, .grep(), .fields(), sort() available):
0: hello

In [7]: out = !egg.py 2>&1

In [8]: out
Out[8]: SList (.p, .n, .l, .s, .grep(), .fields(), sort() available):
0: hello
1: Traceback (most recent call last):
2:   File "D:\python\note\egg.py", line 7, in <module>
3:     main()
4:   File "D:\python\note\egg.py", line 5, in main
5:     print 3/0
6: ZeroDivisionError: integer division or modulo by zero

希望这有帮助

foo 2>&1 means redirect all of the output, including handle 2 (that is, STDERR), from the foo command to handle 1 (that is, STDOUT)
so here out = !foo 2>&1 maybe good enough. below is the demo:
egg.py:

#!/usr/bin/env python
# -*- coding: utf8 -*-
def main():
    print 'hello'
    print 3/0
if __name__ == "__main__":
    main()

IPython 0.10

In [5]: out = !egg.py
Traceback (most recent call last):
  File "D:\python\note\egg.py", line 7, in <module>
    main()
  File "D:\python\note\egg.py", line 5, in main
    print 3/0
ZeroDivisionError: integer division or modulo by zero

In [6]: out
Out[6]: SList (.p, .n, .l, .s, .grep(), .fields(), sort() available):
0: hello

In [7]: out = !egg.py 2>&1

In [8]: out
Out[8]: SList (.p, .n, .l, .s, .grep(), .fields(), sort() available):
0: hello
1: Traceback (most recent call last):
2:   File "D:\python\note\egg.py", line 7, in <module>
3:     main()
4:   File "D:\python\note\egg.py", line 5, in main
5:     print 3/0
6: ZeroDivisionError: integer division or modulo by zero

Hope this helps

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文