• 【python】print · sys.stdout · sys.stderr


    参考文档

    Python重定向标准输入、标准输出和标准错误

    http://blog.csdn.net/lanbing510/article/details/8487997

    python重定向sys.stdin、sys.stdout和sys.stderr

    http://www.cnblogs.com/guyuyuan/p/6885448.html

    1.print

    print obj 事实上是调用了sys.stdout.write(obj+' '),注意多了一个换行符

    1a. print在python 2.X 和 python 3 上的区别

    python 3  的print 函数应该是多了两个选项参数: end, file

    • end可以控制print结尾是换行、不换行、或是其他字符
    #不换行
    print("xx",end='')
    • file可以控制输出为sys.stdout 还是sys.stderr
    print("XXX",sys.stderr)
    

    2.sys.stdout和sys.stderr   

    2a.定义

    '''

    标准输出和标准错误(通常缩写为 stdout 和 stderr)是建立在每个UNIX系统内的管道(pipe)

    当你 print 某东西时,结果输出到 stdout 管道中;当你的程序崩溃并打印出调试信息时(象Python中的错误跟踪),结果输出到 stderr 管道中。

    通常这两个管道只与你正在工作的终端窗口相联,所以当一个程序打印输出时,你可以看到输出,并且当一个程序崩溃时,你可以看到调试信息。(如果你在一个基于窗口的Python IDE系统上工作,stdout 和 stderr 缺省为“交互窗口”。) 

    '''

    2b.使用

    '''

    stdout 和 stderr 都是类文件对象,就象我们在提取输入源中所讨论的一样,但它们都是只写的。它们没有 read 方法,只有 write。

    然而,它们的确是类文件对象,并且你可以将任意文件对象或类文件对象赋给它们来重定向输出

    '''

    2c.缓冲

    sys.stdout是有缓冲区的,解决缓冲有两种方式:

    • print() 或者sys.stdout.write()后加sys.stdout.flush()
    • 执行python脚本时增加-u 参数,即 python -u XXX.py

    3. 特殊情况CGI 以及 重定向输出

    通过以上可知原始的 stdout 和 stderr都是指向控制台

    3a.CGI 的stdout

    如果使用python 编写CGI脚本,此时stdout是指向输出的网页的,stderr依然指向控制台

    所以直接使用print XXX,XXX是直接生成到页面中的;如果要调试打log,有两种方法:

    • 通过stderr来输出;
    • 临时修改stdout,使其指向控制台,即重定向输出

    3b.重定向输出

    • 重定向输出到文件
    f_handler=open('out.log', 'w') 
    
    sys.stdout=f_handler 
    print 'hello'
    • 重定向输出到标准输出
    #!/usr/bin/env python
    
    import cgi
    
    # 在CGI脚本下,sys.stdout输出到网页
    web_out = sys.stdout    # 保存下输出到网页的状态
    
    sys.stdout = sys.stderr    # 将标准输出改成控制台
    sys.stdout.write('sys.stdout -> console')    # 通过sys.stdout打印信息到控制台
    print("print -> console")    # 通过print打印信息到控制台
    
    sys.stdout = web_out    # 将标准输出改成网页
    sys.stdout.write('sys.stdout -> web')    # 通过sys.stdout打印信息到网页
    print("print -> web")    # 通过print打印信息到网页
     
    

      

    聊干净了,结束~

  • 相关阅读:
    The content of the adapter has changed but ListView did not receive a notification. Make sure the content of your adapter is not modified from a background thread, but only from the UI thread. Make s
    ScrollView 定位
    Fragment获取Activity,Activity获取Fragment
    Popupwindow全屏问题
    bzoj千题计划310:bzoj5285: [Hnoi2018]寻宝游戏(思维题+哈希)
    bzoj千题计划309:bzoj4332: JSOI2012 分零食(分治+FFT)
    2016vijos 1-3 兔子的晚会(生成函数+倍增FWT)
    bzoj千题计划308:bzoj4589: Hard Nim(倍增FWT+生成函数)
    bzoj千题计划307:bzoj5248: [2018多省省队联测]一双木棋
    cdqz2017-test10-加帕里图书馆(区间DP & 简单容斥)
  • 原文地址:https://www.cnblogs.com/silvi/p/7260506.html
Copyright © 2020-2023  润新知