V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
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 · 2016-07-13 13:31:03 +08:00 · 3335 次点击
    这是一个创建于 2855 天前的主题,其中的信息可能已经有所发展或是发生改变。
    #!/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 条回复    2016-07-13 15:27:44 +08:00
    shyling
        1
    shyling  
       2016-07-13 13:33:52 +08:00 via iPad
    可以用\b 退格
    可以用 termios 之类的 api
    DuckJK
        2
    DuckJK  
    OP
       2016-07-13 14:11:02 +08:00
    @shyling \b 的退格只会对一行起作用
    felixzhu
        3
    felixzhu  
       2016-07-13 14:20:37 +08:00   ❤️ 2
    如果不换行的话'\r'才有用吧

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

    看看是不是你要的效果
    pixstone
        4
    pixstone  
       2016-07-13 14:33:18 +08:00
    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
       2016-07-13 15:27:44 +08:00
    @pixstone \r 只会对当前那一行有作用,所以在加了\n 只会就会失效。
    @felixzhu 这个没问题,\033[nA 是光标上移 n 行,可以先计算有多少输出数据,然后再上移输出。另外找了下这个是 \033[2J 清屏,非常感谢。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3803 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 04:58 · PVG 12:58 · LAX 21:58 · JFK 00:58
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.