In python, can I redirect the output of print function to stderr?

前端 未结 3 551
难免孤独
难免孤独 2021-01-04 13:52

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

相关标签:
3条回答
  • 2021-01-04 14:32

    Do this in your method:

    import sys
    sys.stdout = sys.stderr
    
    0 讨论(0)
  • 2021-01-04 14:34

    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)
    
    0 讨论(0)
  • 2021-01-04 14:37

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

    See: another question

    0 讨论(0)
提交回复
热议问题