亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

我怎樣才能有一個每秒更新一次的實時計時器來查看我的程序運行了多少?

我怎樣才能有一個每秒更新一次的實時計時器來查看我的程序運行了多少?

哆啦的時光機 2023-06-27 17:35:22
有沒有辦法制作一個每秒更新一次的計時器,這樣我就可以看到我的程序運行了多長時間。我嘗試制作一個循環:i = 0for 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'))“Up-Time”是我想要顯示時間的地方,但是當我嘗試運行它時,什么也沒有顯示。但是當我將 print(i) 放在循環下面時,它唯一做的就是打印出數字,而不運行實際的服務器。如果解釋不夠好,我很抱歉,我對 StackOverFlow 和一般編程非常陌生。抱歉,如果打擾您,先謝謝您!
查看完整描述

2 回答

?
ABOUTYOU

TA貢獻1812條經驗 獲得超5個贊

您可以通過多線程來完成此任務。您讓函數與您的時間一起運行,并且函數運行完畢后兩者都會立即終止:


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!')


查看完整回答
反對 回復 2023-06-27
?
RISEBY

TA貢獻1856條經驗 獲得超5個贊

您永遠不應該使用time.sleepwithdiscord.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")

現在您可以使用{prefix}uptime它來了解它已經運行了多長時間。


查看完整回答
反對 回復 2023-06-27
  • 2 回答
  • 0 關注
  • 187 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號