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

目标:

  1.使用sys.stdout.write模拟火车道轨迹变化过程

  2.使用sys.stderr.write模拟火车道轨迹变化过程

 

1.sys.stdout.write模拟火车道轨迹变化

代码如下:

[root@localhost python]# vim railway.py

[root@localhost python]# cat railway.py
#!/usr/bin/env python
#coding:utf8

import sys,time

width = 20
i = 0
while True:
    sys.stdout.write('%s%s%s\r' %('#' * i, 'a', '#' * (width - i)))
    i +=1
    sys.stdout.flush()
    time.sleep(0.2)
    if i > width:
        i = 0
    #打印出每行的过程,注释print会出现a字符从首字符跑到末尾,然后继续重复上面的工作,及模拟火车道的轨迹。
    print

•运行代码,测试效果

[root@localhost python]# python railway.py

a####################
#a###################
##a##################
###a#################
####a################
#####a###############
######a##############
#######a#############
########a############
#########a###########
##########a##########
###########a#########
############a########
#############a#######
##############a######
###############a#####
################a####
#################a###
##################a##
###################a#
####################a
a####################
#a###################
##a##################

*提示:代码中的print是为了打印上面每一步的变化过程,将print注释重新运行,就会看到a从头到尾不断变化(在一行之中),实现模拟火车道轨迹变化的过程。

 

2.sys.stderr.write模拟火车道轨迹变化(该代码注释了print)

代码如下:

[root@localhost python]# cat railway.py

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

import sys,time

width = 20
i = 0
while True:
    sys.stderr.write('%s%s%s\r' %('#' * i, 'a', '#' * (width - i)))
    i +=1
    time.sleep(0.2)
    if i > width:
        i = 0

•运行代码,测试效果

 

posted @ 2017-01-03 18:56  xkops  阅读(328)  评论(0编辑  收藏  举报