我怎么有一个实时计时器,每秒更新一次,以查看我的程序正在运行多少?蟒蛇

问题描述

有什么方法可以使计时器每秒更新一次,以便我可以看到我的程序运行了多长时间。我试着做一个循环:

i = 0
for i in range(1000000):
    i += 1
    time.sleep(1)

然后我想将其打印到我的discord.py机器人中。看起来是这样的:

async def on_ready():
    os.system('cls')
    print('',fg('red'))
    print(' _____ _                         ',fg('red'))
    print('|  ___| | __ _ _ __  _ __  _   _ ',fg('red'))
    print("| |_  | |/ _` | '_ \| '_ \| | | |",fg('red'))
    print('|  _| | | (_| | |_) | |_) | |_| |',fg('red'))
    print('|_|   |_|\__,_| .__/| .__/ \__,|',fg('red'))
    print('              |_|   |_|     |___/ ',fg('red'))
    print(f'Up-Time: {i}')
    print(f'Version: {version}',fg('blue'))
    print('~~~~~~~~~~~~~~~~~~~~~~~~~~~~',fg('green'))
    print('[Server]: The Bot is online.',fg('green'))

“正常运行时间”是我希望显示间的地方,但是当我尝试运行它时,什么都没有显示。但是,当我将print(i)放在循环下面时,它唯一要做的就是打印出数字,而没有实际的服务器运行。

很抱歉,如果解释不够好,对于StackOverFlow和一般编程而言,它们是全新的。很抱歉打扰您,谢谢您!

解决方法

您永远不要将@http.route('/get_sales',type='json',auth='user') def get_sales(self): sales_rec = request.env['sale.order'].search([]) sales = [] for rec in sales_rec: vals = { 'id': rec.id,'name': rec.name,'partner_id': rec.partner_id,} sales.append(vals) data = {'status': 200,'response': sales,'message': 'All sales returned'} return data time.sleep一起使用,因为它将停止您应该使用discord.py的整个机器人。

您还可以创建此命令。

await asyncio.sleep(1)

现在您可以使用import datetime as dt bot.launch_time = dt.datetime.utcnow() @bot.command() async def uptime(ctx): delta_uptime = dt.datetime.utcnow() - bot.launch_time hours,remainder = divmod(int(delta_uptime.total_seconds()),3600) minutes,seconds = divmod(remainder,60) days,hours = divmod(hours,24) await ctx.send(f"{days}d,{hours}h,{minutes}m,{seconds}s") ,它会告诉您已经运行多长时间了。

,

您可以通过多线程完成此操作。您可以同时运行函数,并且两个函数都在运行完成后立即终止:

import threading 
import time 

def calc(): #this function generates the square of all numbers between 1 and 56000000
    for i in range(1,56000000):
    i*i

t1 = threading.Thread(target=calc) 
t1.start() #starting a thread with the calc function
i = 1
while t1.is_alive(): #Check if the thread is alive
    time.sleep(1)# print time after every second
    print(f'Time elapsed ----------- {i}s')
    i = i+1
t1.join() #terminate thread once calc function is done 
print('Done!')