Skip to main content
 首页 » 编程设计

python之使用 Python 更新先前打印的行(在 CLI 中)

2024年10月17日10bluestorm

我正在用 Python 开发一个命令行游戏,我想实现一个函数来限制玩家回答问题的时间。基本上我想做的是将第一行(打印后)更新为:

    "5.." 
    "5 + 3 = ?" 

到:

   "5..4..3..2..1..Lost" 
   "5 + 3 = ?" 

5秒后


    print "5..3..2..1..Lost" 
    print "5 + 3 = ?" 

请您参考如下方法:

print(num, end='\r')

end= 关键字是有效的原因,print() 以换行符 \n 结束,但这可以替换为任何字符串,例如以回车符结尾的行,都会将光标返回到当前行的开头。您将需要 from __future__ import print_function with python2.7

至于同时接收输入你需要使用threading模块并在线程中打印更新计数器

import time 
from _thread import * 
def printcount(secs): 
    i=5 
    while i != 0: 
        print(i, end='\r') 
        i -= 1 
        time.sleep(secs) 
 
start_new_thread(printcount, (1))