![](/img/trans.png)
[英]“return someString and partString in someString” in Python3
[英]Python3: print(somestring,end='\r', flush=True) shows nothing
我正在編寫一個進度條, 如何為命令行設置動畫? 提示。 我使用Pycharm並在運行工具窗口中運行此文件。
import time
def show_Remaining_Time(time_delta):
print('Time Remaining: %d' % time_delta, end='\r', flush=True)
if __name__ == '__main__':
count = 0
while True:
show_Remaining_Time(count)
count += 1
time.sleep(1)
但是,如果我運行此.py文件,代碼將不顯示任何內容。 我究竟做錯了什么?
我試過Jogger的建議,但如果我使用print
功能它仍然無法正常工作。
但是,以下腳本按預期工作。
import time
import sys
def show_Remaining_Time(time_delta):
sys.stdout.write('\rtime: %d' % time_delta) # Doesn't work if I use 'time: %d\r'
sys.stdout.flush()
if __name__ == '__main__':
count = 0
while True:
show_Remaining_Time(count)
count += 1
time.sleep(1)
我現在有兩個問題:
為什么stdout工作但print()沒有。
為什么如何設置命令行的動畫? 建議將\\r
添加到最后,而我必須在我的情況下在開頭寫它?
問題是最后的'\\ r'清除了你剛打印的那條線,怎么樣?
import time
def show_Remaining_Time(time_delta):
print("\r")
print('Time Remaining: %d' % time_delta, flush=True)
if __name__ == '__main__':
count = 0
while True:
show_Remaining_Time(count)
count += 1
time.sleep(1)
通過這種方式,您首先清除該行,然后打印所需的顯示,在睡眠期間將其保留在屏幕中。
此方法可以在同一命令行中打印:
import time
def show_Remaining_Time(time_delta):
print(' \r%d:Time Remaining' % time_delta, end = '',flush=False)
if __name__ == '__main__':
count = 0
while True and count < 10:
show_Remaining_Time(count)
count += 1
time.sleep(1)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.