推荐学习书目
› 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

关于 print 不换行

  •  
  •   hhrmatata · Jul 9, 2014 · 7200 views
    This topic created in 4510 days ago, the information mentioned may be changed or developed.
    python 2.7

    想将两次输出输出到同一行上,就在print 后面加了逗号,例如:

    import time

    print 'hehe ...',
    time.sleep(5)
    print 'finish!'

    但是有个问题,观察终端中的输出,发现观察到的程序的执行顺序是
    1. time.sleep(5)
    2. print 'hehe ...',
    3. print 'finish!'

    如何做到,先输出第一个print,再睡眠,最后输出第二个输出?两个输出在同一行。
    Supplement 1  ·  Jul 10, 2014
    已解决。
    最后定义了这样一个函数就好了:

    def p(s):
    sys.stdout.write(s)
    sys.stdout.flush()
    return None
    14 replies  •  2014-07-11 01:29:58 +08:00
    cj1324
    cj1324
    Jul 9, 2014❤️1
    1
    直接用import sys; sys.stdout ?
    Ansen
    Ansen
    Jul 9, 2014❤️1
    3
    为啥 我这里是按顺序执行的
    hhrmatata
    hhrmatata
    OP
    Jul 9, 2014
    4
    @cj1324
    @pinepara
    谢谢

    最后定义了这样一个函数就好了:

    def p(s):
    sys.stdout.write(s)
    sys.stdout.flush()
    return None
    cj1324
    cj1324
    Jul 9, 2014❤️1
    6
    @hhrmatata
    return None 不就是 return ? 这样写反而更让人疑惑。
    wy315700
    wy315700
    Jul 9, 2014❤️1
    7
    终端的输出刷新是按行来的,除非手动调用flush
    mengzhuo
    mengzhuo
    Jul 9, 2014❤️1
    8
    @hhrmatata 不要观察执行顺序,ipdb是你debug的好伙伴
    shyrock
    shyrock
    Jul 9, 2014❤️1
    9
    python2.7.6 执行是对的啊。。。
    hehe ... finish!
    [Finished in 5.1s]
    Ever
    Ever
    Jul 9, 2014❤️1
    10
    不用return就是return None

    python3可以print(word, end="")

    python2.7可以from __future__ import print_function后照python3的做
    Cynic222
    Cynic222
    Jul 9, 2014❤️1
    11
    @cj1324
    不写return不就是return None?这样写反而更让人疑惑。-- 开个玩笑
    cakegg
    cakegg
    Jul 9, 2014❤️1
    12
    import sys
    import time
    print "hello",
    stdout_temp = sys.stdout
    time.sleep(5)
    sys.stdout = stdout_temp
    print "finish"

    其实像上面这样写就可以了...
    hhrmatata
    hhrmatata
    OP
    Jul 10, 2014 via Android
    13
    @cj1324
    @Cynic222
    个人习惯问题,方便阅读。明确告诉阅读代码的人是返回空而不是忘记写了。
    ggarlic
    ggarlic
    Jul 11, 2014❤️1
    14
    这,,,,完全不用改代码啊
    python -u xx.py
    让python运行在unbuffered的模式不就行了
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   961 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 41ms · UTC 19:44 · PVG 03:44 · LAX 11:44 · JFK 14:44
    ♥ Do have faith in what you're doing.