12

There're lots of print function (python 2.7) in my program. Is there any way I can add a few lines then all the output can be redirected to stderr? What I want is python codes but not linux pipeline.

For example, my program is like:

print 'hello world' 

I would like to add some codes like:

redirect_output_to_stderr() print 'hello world' 

Then all the output can be redirected to stderr.

I know print >> sys.stderr, 'hello world' can achieve my goal, but is it any way that can prevent from modifying the existed codes?

2
  • 1
    The only way to do that without modifying the code is to use a shell's redirection commands. Commented Apr 7, 2013 at 8:42
  • Oh, I guess what I need is preventing from modified the existed print functions. Thank you for mentioned that :) Commented Apr 7, 2013 at 8:45

3 Answers 3

20

In python 2.7 you can do:

import sys print >> sys.stderr, "To stderr." 

Or you can import the behavior from 3.x:

from __future__ import print_function import sys print('To stderr.', file=sys.stderr) 
Sign up to request clarification or add additional context in comments.

Comments

8

Do this in your method:

import sys sys.stdout = sys.stderr 

2 Comments

Or maybe don't, god this is horrible advice.
@ruohola Yeah, not a great thing to do in any code, even 6 years ago! But I guess this is exactly what the question was asking for ¯_(ツ)_/¯
1

Redefinition of print is feature of Python 3+. However, you can change sys.stdout to std.stderr.

See: another question

2 Comments

You can redefine print in 2.7 if you do from __future__ import print_function.
@lvc Didn't know that. Still change of stdout is shorter than function redefinition.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.