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 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

4 Comments

sunqiang: UNIX had this sort of redirection (2>&1 to duplicate <i>stderr</i> to <i>stdout</i>, for example) long before MS added support for it in their systems. Under UNIX it's generalized (you can redirect, duplicate and close other file descriptors if you know their numbers).
@Jim Dennis, thanks for the info. I am just a Linux newbie. don't know this before. I have edited the answer correspondingly.
would you happen to know if one can capture the output of a macro?
@Geo, sorry I don't know macro.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.