views:

246

answers:

1

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?

+1  A: 

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

sunqiang
Jim Dennis
@Jim Dennis, thanks for the info. I am just a Linux newbie. don't know this before. I have edited the answer correspondingly.
sunqiang
Thanks! It does help.
Geo
@Geo, you are welcome:)
sunqiang
would you happen to know if one can capture the output of a macro?
Geo
@Geo, sorry I don't know macro.
sunqiang