sys.stdout.write与sys.sterr.write(三)

目标:

  1.使用sys.stdout.write模拟"|"的顺时针变化— \ | / 

  2.使用sys.stderr.write模拟"|"的顺时针变化— \ | /

 

1.sys.stdout.write模拟"|"的顺时针变化

代码如下:

[root@localhost python]# cat animation.py

#!/usr/bin/env python
#coding:utf8

import sys,time

for i in xrange(10):
    for ch in '-\\|/':
        print '%-20s%s\r' % ('waiting...', ch)
        #sys.stdout.write('%-20s%s\r' % ('waiting...', ch))
        sys.stdout.flush()
        time.sleep(0.2)

•运行代码,测试效果

[root@localhost python]# python animation.py

waiting...          -
waiting...          \
waiting...          |
waiting...          /
waiting...          -
waiting...          \
waiting...          |
waiting...          /
waiting...          -
waiting...          \
waiting...          |
waiting...          /
waiting...          -
waiting...          \
waiting...          |
waiting...          /
waiting...          -
waiting...          \
waiting...          |
waiting...          /
waiting...          -
waiting...          \
waiting...          |
waiting...          /
waiting...          -
waiting...          \
waiting...          |
waiting...          /
waiting...          -
waiting...          \
waiting...          |
waiting...          /
waiting...          -
waiting...          \
waiting...          |

*提示:上述代码使用print是为了打印代码的过程,将print代码行注释,打开sys.stdout.write代码行,重新运行,即可看到"|"顺时针变化的效果。

 

2.sys.stderr.write模拟"|"的顺时针变化

代码如下:

[root@localhost python]# cat animation.py

#!/usr/bin/env python
#coding:utf8

import sys,time

for i in xrange(10):
    for ch in '-\\|/':
        #print '%-20s%s\r' % ('waiting...', ch)
        sys.stderr.write('%-20s%s\r' % ('waiting...', ch))
        #sys.stdout.flush()
        time.sleep(0.2)

•运行代码,测试效果

*提示:使用sys.stderr.write没有缓存,注释sys.stdout.flush()

posted @ 2017-01-04 10:46  xkops  阅读(1431)  评论(0编辑  收藏  举报