V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
推荐学习书目
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
zbl430
V2EX  ›  Python

各位大佬请进,有点小问题( Python \r)

  •  1
     
  •   zbl430 · Sep 15, 2017 · 2277 views
    This topic created in 3150 days ago, the information mentioned may be changed or developed.
    In [13]: for i in range(1, 5):
        print '\r{0}'.format(i),
        time.sleep(1)
       ....:     
    4 
    
    In [14]: for i in range(1, 5):
        print '{0}\r'.format(i),
        time.sleep(1)
       ....:     
    4
    
    

    上面都是只在最后才打印一个 4,不能 1, 2, 3, 4 的在同一行循环显示,就像下载进度条增量改变一样,请大佬指教

    10 replies    2017-09-15 16:24:21 +08:00
    zbl430
        1
    zbl430  
    OP
       Sep 15, 2017
    ```
    for i in range(1, 5):
    dd = '.'*i
    sys.stdout.write(dd+'\r')
    sys.stdout.flush()
    time.sleep(1)

    ```
    这样可以了,但是 print 依旧不知如何实现
    keysona
        2
    keysona  
       Sep 15, 2017
    python3


    import time

    for i in range(100):
    time.sleep(1)
    print('\r{}%'.format(i), end='', flush=True)
    John60676
        3
    John60676  
       Sep 15, 2017
    你的意思是 print 输出时不换行吗? py3 可以 print(i,end="") ,py2 可以 print i,
    keysona
        4
    keysona  
       Sep 15, 2017
    python2 的 print 会换行的。

    python3 可以取消。
    JimmyMu
        5
    JimmyMu  
       Sep 15, 2017
    for i in range(1, 5):
    print '{0} '.format(i),
    sys.stdout.flush()
    sleep(1)
    keysona
        6
    keysona  
       Sep 15, 2017
    @JimmyMu

    一个逗号居然可以去换行,见识了!
    John60676
        7
    John60676  
       Sep 15, 2017   ❤️ 1
    @keysona py2 可以在后面加个逗号取消
    ltux
        8
    ltux  
       Sep 15, 2017
    python 2.X 无法用 print 实现,即使 from __future__ improt print_function,print() 函数也不支持 flush 参数。
    ltux
        9
    ltux  
       Sep 15, 2017
    不能 flush 就无法实现。
    zbl430
        10
    zbl430  
    OP
       Sep 15, 2017
    @JimmyMu 是这样的,但是需要依赖 sys.stdout.flush() ,谢了
    @ltux 说的对
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1226 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 37ms · UTC 17:15 · PVG 01:15 · LAX 10:15 · JFK 13:15
    ♥ Do have faith in what you're doing.