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

前端 未结 3 550
难免孤独
难免孤独 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: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)
    

提交回复
热议问题