简体   繁体   English

Spyder中的Python time.sleep:如何在print语句之间暂停?

[英]Python time.sleep in Spyder: how to pause between print statements?

Edit: the linked post does not solve this problem, this is still an outstanding issue. 编辑:链接的帖子没有解决这个问题,这仍然是一个突出的问题。

I execute the following program in Spyder with iPython: 我用Spython在Spyder中执行以下程序:

import time

print "Please enter your name."
userName=raw_input();
print "Now let's wait a few seconds, {}.".format(userName)
time.sleep(1)
print "Did you lose your patience?"

It prompts the user for their name, then (instead of printing the first line, waiting, and then printing the second line), it pauses and then prints the outputs of the last two print statements at the same time. 它提示用户输入他们的名字,然后(而不是打印第一行,等待,然后打印第二行),它会暂停,然后同时打印最后两个打印语句的输出。

When I run from the command line, it works as expected. 当我从命令行运行时,它按预期工作。 So does anyone know what I can do so that the script shows the desired behavior from within Spyder/iPython (I am working in Windows 7, Spyder 2.2.5 running iPython with Python 2.7). 所以有人知道我能做什么,以便脚本在Spyder / iPython中显示所需的行为(我在Windows 7中运行,Spyder 2.2.5在Python 2.7中运行iPython)。

Note because I get the expected behavior when I run from the command line, the suggestion at Why is time.sleep pausing early? 请注意,因为当我从命令行运行时,我得到了预期的行为, 为什么time.sleep提前暂停? is not transparently applicable, but perhaps it is easy to port that solution to this case? 是不是透明适用,但也许很容易将解决方案移植到这种情况? Also, running 'sys.stdout.flush()' before the sleep command doesn't seem to do anything. 此外,在sleep命令之前运行'sys.stdout.flush()'似乎没有做任何事情。

I tested this in Spyder and vanza's solution works for me. 我在Spyder测试了这个,vanza的解决方案适合我。 Are you sure you put sys.stdout.flush() in the right line? 你确定你把sys.stdout.flush()放在正确的行吗? It should look like this: 它应该如下所示:

vanza's solution:

import time
import sys

print "Please enter your name."
userName=raw_input();
print "Now let's wait a few seconds, {}.".format(userName)
sys.stdout.flush() # <- *** it goes here ***
time.sleep(3)
print "Did you lose your patience?"

You might want to scroll down the iPython console a bit before entering your input, to see the text clearly (otherwise it stays a bit low to be noticed). 在输入输入之前,您可能需要稍微向下滚动iPython控制台,以便清楚地看到文本(否则它会保持有点低而不被注意到)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM