我正在编写一个处理程序输出的 ipython 宏。问题是,程序有时可以写入stderr
,所以如果我做这样的事情:
out = !my_program
该out
变量将不包含输出。我认为它将包含退出代码(如果我错了,请纠正我)。
如何捕获 stdout 和 stderr 流?
foo 2>&1 表示将所有输出,包括句柄 2(即 STDERR)从 foo 命令重定向到句柄 1(即 STDOUT)
,所以这里 out = !foo 2>&1 可能就足够了。下面是演示:
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
希望这可以帮助