[英]How do I print in Python 3.3.3 without carriage return?
首先,我不是在尋找如何在print(some_stuff, end="")
的同一行中print(some_stuff, end="")
。
在Python 2.7中,您可以輸入:
while True:
for i in ["/","-","|","\\","|"]:
print "%s\r" % i,
並且它會在相同的行中打印出SAME中的那5個字符,使它看起來像是一個條形旋轉(實際上你可以嘗試一下)。 問題是,我不能在Python 3.3中做同樣的事情,我已經嘗試了幾件事。 我的具體應用是倒數計時器...代碼是這樣的:
import time
t = 120
while t > 0:
t -= 1
print("Time left till next update: %d seconds" % t)
time.sleep(1)
輸出應該是字符串,只有在適當的位置改變的秒數...希望有人可以幫我這個。
您使用end='\\r'
作為關鍵字參數:
print("Time left till next update: %d seconds" % t, end='\r')
end
的默認值為'\\n'
但您可以指定自己的。
您還可以嘗試更低級別: fd=1
( sys.stdin
)上的os.write(fd, data)
)。
請注意, data
必須是bytes
( b'whatever data'
)。
import os, time
os.write(1, b'Time left till next update: 120 seconds'+b'\b'*8)
t=120
while t>0:
time.sleep(1)
t -= 1
os.write(1, b'\b'*3+str(t).zfill(3).encode())
print()
它在終端中正常工作,但Python IDLE忽略'\\r'
和'\\b'
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.