推荐学习书目
› Learn Python the Hard Way
Python Sites
› PyPI - Python Package Index
› http://diveintopython.org/toc/index.html
› Pocoo
值得关注的项目
› PyPy
› Celery
› Jinja2
› Read the Docs
› gevent
› pyenv
› virtualenv
› Stackless Python
› Beautiful Soup
› 结巴中文分词
› Green Unicorn
› Sentry
› Shovel
› Pyflakes
› pytest
Python 编程
› pep8 Checker
Styles
› PEP 8
› Google Python Style Guide
› Code Style from The Hitchhiker's Guide
DuckJK
V2EX  ›  Python

Python 输出刷新的问题

  •  
  •   DuckJK · Jul 13, 2016 · 4146 views
    This topic created in 3730 days ago, the information mentioned may be changed or developed.
    #!/usr/bin/python
    # coding:utf-8
    import sys
    import time
    import os
    
    urls = ['http://one.com/1', 'http://one.com/2', 'http://one.com/3']
    
    while 1:
    	date_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
    	sys.stdout.write('%s\n' % date_time)
    	for url in urls:
    		sys.stdout.write('%s\n' % url)
    	time.sleep(2)
    	os.system('clear')
    	
    

    像这种输出之后把已经输出的清空,再输出下一次还有别的方法么?试了下'\r',但是没达到预期效果,其中 urls 是一个变量,定时更新。

    谢谢

    5 replies  •  2016-07-13 15:27:44 +08:00
    shyling
        1
    shyling  
       Jul 13, 2016 via iPad
    可以用\b 退格
    可以用 termios 之类的 api
    DuckJK
        2
    DuckJK  
    OP
       Jul 13, 2016
    @shyling \b 的退格只会对一行起作用
    felixzhu
        3
    felixzhu  
       Jul 13, 2016   ❤️ 2
    如果不换行的话'\r'才有用吧

    你把最后一行换成
    sys.stdout.write('\033[4A')

    看看是不是你要的效果
    pixstone
        4
    pixstone  
       Jul 13, 2016
    python curses 用这个

    或者这个 case (来自 StackOverflow )
    import sys
    import time

    for i in range(20):
    sys.stdout.write("\r{0}>".format("="*i))
    sys.stdout.flush()
    time.sleep(0.5)
    DuckJK
        5
    DuckJK  
    OP
       Jul 13, 2016
    @pixstone \r 只会对当前那一行有作用,所以在加了\n 只会就会失效。
    @felixzhu 这个没问题,\033[nA 是光标上移 n 行,可以先计算有多少输出数据,然后再上移输出。另外找了下这个是 \033[2J 清屏,非常感谢。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   5249 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 03:06 · PVG 11:06 · LAX 20:06 · JFK 23:06
    ♥ Do have faith in what you're doing.