2014-05-19 22 views
0

我有這樣的代碼:time.sleep()在Python Shell不同的工作比在命令窗口

print(nextaction + ' ', end="") 
time.sleep(2) 
print(nextplayer+"'s ", end="") 
time.sleep(1) 
print(nextitem + '!') 
time.sleep(3) 

當我在shell中運行這個與F5,它正常工作和pauzes秒的給定數量。但是當我在命令窗口中運行時,只需雙擊文件夾中的PGM,它只會執行第一次暫停(打印行之前),然後立即打印所有內容。

爲了清楚起見,最終的行總是像「殺邁克的狗!」。但我希望在每個單詞之間有一段暫停。

我不知道爲什麼會發生這種情況。

+2

輸出緩衝區。如果你想強制輸出到控制檯,你需要刷新輸出流:'import sys; sys.stdout.flush()'。 – Holt

回答

1

您需要刷新輸出,因爲在命令行沒有按」 t自動爲你做(除非有一個換行符,或一定數量的字符已被寫入sys.stdout)。 print()函數有一個可選參數,可讓您指定是否刷新或不刷新。

print(nextaction, end=' ', flush=True) 
time.sleep(2) 
print(nextplayer, end="'s", flush=True) 
time.sleep(1) 
print(nextitem+'!', flush=True) # there is a newline, so no need to flush it 
time.sleep(3) 
1

您需要刷新輸出。在REPL中,輸出會自動刷新以允許打印提示。

2

命令窗口有一個緩衝區,在一定數量的字符後或在每個新行後刷新。在這裏,你沒有足夠的字符或新行來執行它,所以你需要給力了:

import sys 
print(nextaction + ' ', end="") 
sys.stdout.flush() 
time.sleep(2) 
# Also possible inline through the print function (Python 3 only) 
print(nextplayer+"'s ", end="", flush=True) 
time.sleep(1) 
print(nextitem + '!') # Should not be useful there, since there is the \n 
time.sleep(3) 

參見:How to flush output of Python print?

+0

已過時。查看您發佈的鏈接的最後一個答案。 –

+0

@Scorpion_God固定。如果用戶仍然在Python 2上(即使他可以使用'__future__ print_function'),我已經離開了舊的解決方案。 –

相關問題