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
hhrmatata
V2EX  ›  Python

独立于操作系统的carriage return

  •  
  •   hhrmatata · 2013-04-24 16:24:35 +08:00 · 3168 次点击
    这是一个创建于 4019 天前的主题,其中的信息可能已经有所发展或是发生改变。
    python有独立于操作系统的换行符os.linesep

    现在我想返回到同一行行首,一般是\r,但是这个字符的表现跟操作系统有关,有不有类似os.linesep这种替换?
    8 条回复    1970-01-01 08:00:00 +08:00
    Mutoo
        1
    Mutoo  
       2013-04-24 16:35:54 +08:00
    你可以用 terminal codes 来移动光标位置 http://wiki.bash-hackers.org/scripting/terminalcodes
    hhrmatata
        2
    hhrmatata  
    OP
       2013-04-25 15:25:03 +08:00
    @Mutoo 不明白这个是做什么。python中有相应实现吗?
    Mutoo
        3
    Mutoo  
       2013-04-25 16:12:18 +08:00
    @hhrmatata 你想在文件流中 carriage return,还是在终端中 carriage return?终端的话,\r是在各个平台上是通用的。
    况且os.linesep只针对换行,而且对文件的意义比较大。

    terminal codes 可以这样用

    print 'It is \033[31mnot\033[39m intelligent to use \033[32mhardcoded ANSI\033[39m codes!'
    It is not intelligent to use hardcoded ANSI codes!
    Mutoo
        4
    Mutoo  
       2013-04-25 16:18:51 +08:00
    Mutoo
        5
    Mutoo  
       2013-04-25 16:23:08 +08:00
    @hhrmatata print("Hello\033[80DWorld") # \033[80D 向后移动80列(相当于\r)

    http://www.tldp.org/HOWTO/Bash-Prompt-HOWTO/x361.html
    hhrmatata
        6
    hhrmatata  
    OP
       2013-04-26 13:32:24 +08:00
    @Mutoo 我想在终端中用,\r不是各平台通用吧? \r在Mac OS 中表示换行且返回到下一行的最开始位置,相当于linux 里的 \n 的效果。

    表示terminal_control有点过于复杂。

    我的目的很简单,下载的时候在终端同一行显示下载进度,后一个进度覆盖前面一个进度。
    Mutoo
        7
    Mutoo  
       2013-04-26 13:46:11 +08:00   ❤️ 1
    @hhrmatata 你要的这种效果通常是用\b实现的。参考 #Spinning loading bar#

    http://www.stealth-x.com/articles/python-code-tricks.php
    hhrmatata
        8
    hhrmatata  
    OP
       2013-04-27 10:51:30 +08:00
    @Mutoo \b 确实可以比较好地实现, sys.stdout.write(line1 + '\b' * len(line1) + line2)

    你给的这个博客效果不错啊,很简单地实现了loading...的效果,特别是多线程的考虑比较周到。

    非常欣赏博主“Why I hate nerds”这篇文章,尤其作者才17岁,中国教育要加油啊!

    最后感谢 @Mutoo 这么耐心的答复。谢谢!
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   4429 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 10:10 · PVG 18:10 · LAX 03:10 · JFK 06:10
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.