【问题】
对于之前一个函数:
#--------------------------------------------------------------------------- # note: totalFileSize -> may be -1 on older FTP servers which do not return a file size in response to a retrieval request def reportHook(copiedBlocks, blockSize, totalFileSize) : #global downloadingFile if copiedBlocks == 0 : # 1st call : once on establishment of the network connection print 'Begin to download %s, total size=%d'%(downloadingFile, totalFileSize); else : # rest call : once after each block read thereafter print 'Downloaded bytes: %d' % ( blockSize * copiedBlocks); return; #---------------------------------------------------------------------------
中间包含打印,但是是每次打印一行后,就换行了,效果如下:
Downloaded bytes: 8192 Downloaded bytes: 24576 Downloaded bytes: 32768 Downloaded bytes: 40960 Downloaded bytes: 49152 Downloaded bytes: 57344 Downloaded bytes: 65536 Downloaded bytes: 73728 Downloaded bytes: 81920 Downloaded bytes: 90112 Downloaded bytes: 98304 Downloaded bytes: 106496 Downloaded bytes: 114688 Downloaded bytes: 122880 Downloaded bytes: 131072 Downloaded bytes: 139264 |
现在希望,可以像有的程序输出一样,始终保持同一行,即新打印出来的一行,替换掉之前的那行,保持同一行,不换行。
【解决过程】
1.尝试了:
print 'Downloaded bytes: %d\r' % ( blockSize * copiedBlocks);
结果不行。
2.后来改为:
print 'Downloaded bytes: %d\r' % ( blockSize * copiedBlocks),;
就可以了,就可以保持,始终是显示在同一行:
Downloaded bytes: 90112 |
效果还是不错的:
【总结】
想要print始终显示在同一行,本身是在最后加上逗号即可,即:
print "xxx",
然后又想要实现,新打印的一行,冲掉之前旧的一行,达到显示出下载文件大小一点点增加,但是却始终保持同行,那么就再打印的内容最后添加上\r即可:
print "xxx\r",
注:
对于\r不熟悉的,可以参考:
【详解】回车 换行 0x0D 0x0A CR LF \r \n的来龙去脉
转载请注明:在路上 » 【已解决】Python中打印输出不换行,始终保持一行