74 lines
2.1 KiB
Python
74 lines
2.1 KiB
Python
import asyncio
|
|
from REPL import REPLApp, RunSync, cmd2
|
|
|
|
class MyApp(REPLApp):
|
|
@RunSync
|
|
async def do_guess_number(self, args):
|
|
"""
|
|
play guess number game
|
|
"""
|
|
import random
|
|
number = random.randint(1, 100)
|
|
await self.print("Guess a number between 1 and 100")
|
|
while True:
|
|
guess = await self.input("Your guess: ")
|
|
if not guess.isdigit():
|
|
await self.print("Please enter a valid number.")
|
|
continue
|
|
guess = int(guess)
|
|
if guess < number:
|
|
await self.print("Too low!")
|
|
elif guess > number:
|
|
await self.print("Too high!")
|
|
else:
|
|
await self.print("Congratulations! You guessed the number.")
|
|
break
|
|
|
|
@RunSync
|
|
async def do_progress(self, args):
|
|
"""
|
|
多行进度条示例
|
|
"""
|
|
import sys
|
|
import asyncio
|
|
|
|
tasks = 3
|
|
total = 30
|
|
progresses = [0] * tasks
|
|
|
|
# 先打印多行空进度条
|
|
for t in range(tasks):
|
|
print(f'任务{t+1}: |{"-"*total}| 0%')
|
|
# 光标回到最上面
|
|
print('\033[F' * tasks, end='')
|
|
|
|
for i in range(total + 1):
|
|
for t in range(tasks):
|
|
bar = '█' * i + '-' * (total - i)
|
|
percent = int(i / total * 100)
|
|
print(f'任务{t+1}: |{bar}| {percent}%')
|
|
# 每次循环后,光标回到最上面
|
|
print('\033[F' * tasks, end='')
|
|
await asyncio.sleep(0.1)
|
|
# 最后打印完成的进度条
|
|
for t in range(tasks):
|
|
bar = '█' * total
|
|
print(f'任务{t+1}: |{bar}| 100%')
|
|
|
|
|
|
async def mainLoop():
|
|
app = MyApp()
|
|
app.preloop()
|
|
try:
|
|
stop = False
|
|
while not stop:
|
|
line = await app.input(app.prompt)
|
|
try:
|
|
stop = app.onecmd_plus_hooks(line)
|
|
except asyncio.CancelledError:
|
|
await app.print("^C: Task cancelled")
|
|
finally:
|
|
app.postloop()
|
|
|
|
if __name__ == "__main__":
|
|
asyncio.run(mainLoop()) |