Runtimewarning enable tracemalloc to get the object allocation traceback ошибка

This post provides the method to solve the error "RuntimeWarning: Enable tracemalloc to get the object allocation traceback" in Python. Let's read it now.

This article discusses the error ‘RuntimeWarning: Enable tracemalloc to get the object allocation traceback‘ in Python. If you are facing the same problem, check out the information below to find out the cause of this error and how to fix it by using the keyword ‘await‘. 

The cause of this error

First, we need to know that ‘asyncio‘ is a library for writing concurrent code using the async/await syntax. The sleep() method of this module is used to delay the currently executing task and allow another task to be executed.

Syntax:

asyncio.sleep(delay, result=None)

The reason why we received the error is that we forgot to use the “await” keyword before the sleep() method.

To illustrate, let me reproduce the error:

import asyncio

async def main():
    print('Loading…')
    
    asyncio.sleep(3)    
    print('Welcome to our site. We are LearnShareIT!')

asyncio.run(main())

Output:

RuntimeWarning: Enable tracemalloc to get the object allocation traceback

To fix this problem, you just need to add the keyword ‘await‘ before calling the sleep() method.

The ‘await‘ keyword is used as the signal to mark the breakpoint. It allows a coroutine to temporarily suspend execution and allow the program to return to it later.

Continuing with the example above, let’s see how we fix this problem:

import asyncio

async def main():
  
    print('Loading…')
    # Add the 'await' keyword in front of the asyncio.sleep() method
    await asyncio.sleep(3)
 
    print('Welcome to our site. We are LearnShareIT!')

asyncio.run(main())

Output:

At this point the error seems to have been solved with just a small change in the code. 

We set the block time to three seconds in the sleep() method. As you can see, the message ‘Loading…‘ appears first, then after ‘3‘ seconds message ‘Welcome to our site. We are LearnShareIT!‘ is printed.

Summary

To sum up, that’s all we want to talk about the error ‘RuntimeWarning: Enable tracemalloc to get the object allocation traceback‘ in Python. To solve this problem, you have to use the ‘await‘ keyword before calling the asyncio.sleep() method. Try it out in your project and see the results. Hopefully, the information we provide in this post will be helpful to you.

Maybe you are interested:

  • RuntimeError: dictionary changed size during iteration
  • Statements must be separated by newlines or semicolons

My name’s Christopher Gonzalez. I graduated from HUST two years ago, and my major is IT. So I’m here to assist you in learning programming languages. If you have any questions about Python, JavaScript, TypeScript, Node.js, React.js, let’s contact me. I will back you up.

Name of the university: HUST
Major: IT
Programming Languages: Python, JavaScript, TypeScript, Node.js, React.js

Написал бота на поддержку, когда задаёшь вопрос сам-себе в диалоге и отвечаешь всё работает. А когда пытаешься ответить другому юзеру то происходит ошибка
Код:

@dp.message_handler(commands=["support"])
async def support(message):
    needHelpFile = open("needHelp.txt", "a")
    if message.chat.id > 0:
        needHelpFile.write(str(message.chat.id) + "n" + str(message.chat.first_name) + "n")
    else:
        needHelpFile.write(str(message.chat.id) + "n" + str(message.chat.title) + "n")
    needHelpFile.close()
    supportFile = open("support.txt", "r")
    supportTeam = set ()
    for line in supportFile:
        supportTeam.add(line.strip())
    supportFile.close()
    await bot.send_message(message.chat.id, "Подождите немного, {0.first_name}! Мы отправили ваше сообщение Гл.Администратору! n Пожалуйста не оставляйте больше сообщений. n Вы находитесь в очереди.".format(message.from_user, bot.get_me()), parse_mode="html")
    for user in supportTeam:
        if message.chat.id > 0:
            await bot.send_message(int(user), str(message.chat.id) + " (" + message.chat.first_name + ")" + ": " + message.text[message.text.find(" "):])
        else:
            await bot.send_message(int(user), str(message.chat.id) + " (" + message.chat.title + ")" + ": " + message.text[message.text.find(" "):])
 
 
@dp.message_handler(commands=["answer"])
async def answer(message):
    supportFile = open("support.txt", "r")
    supportTeam = set ()
    for line in supportFile:
        supportTeam.add(line.strip())
    supportFile.close()
    if str(message.chat.id) in supportTeam:
        needHelp = []
        needHelpFile = open("needHelp.txt", "r")
        for line in needHelpFile:
            needHelp.append(line.strip())
 
        needHelpFile.close()
        for user in supportTeam:
            if message.chat.id > 0:
                await bot.send_message(user, str(message.chat.id) + " (" + message.chat.first_name +")" + ": Отвечает " + needHelp[0] + " (" + needHelp[1] + "): " + message.text[message.text.find(" "):].format(message.from_user, bot.get_me()), parse_mode="html")
            else:
                await bot.send_message(user, str(message.chat.id) + " (" + message.chat.title + ")" + ": Отвечает " + needHelp[0] + " (" + message.chat.title + "): " + message.text[message.text.find(" "):].format(message.from_user, bot.get_me()), parse_mode="html")
        bot.send_message(int(needHelp[0]), "Support" + ": " + message.text[message.text.find(" "):])
 
        with open("needHelp.txt", "r") as nhf:
            lines = nhf.readlines()
        with open("needHelp.txt", "w") as nhf:
            for line in lines:
                if line.strip("n") != needHelp[0] and line.strip("n") != needHelp[1]:
                    nhf.write(line)
    else:
        await bot.send_message(message.chat.id, "У вас нету разрешения на это!".format(message.from_user, bot.get_me()), parse_mode="html")

Ошибка:
C:Users79065DesktopTupaModerationBotmain.py:55: RuntimeWarning: coroutine ‘Bot.get_me’ was never awaited
await bot.send_message(message.chat.id, «Подождите немного, {0.first_name}! Мы отправили ваше сообщение Гл.Администратору! n Пожалуйста не оставляйте больше сообщений. n Вы находитесь в очереди.».format(message.from_user, bot.get_me()), parse_mode=»html»)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
C:Users79065DesktopTupaModerationBotmain.py:79: RuntimeWarning: coroutine ‘Bot.get_me’ was never awaited
await bot.send_message(user, str(message.chat.id) + » (» + message.chat.first_name +»)» + «: Отвечает » + needHelp[0] + » (» + needHelp[1] + «): » + message.text[message.text.find(» «):].format(message.from_user, bot.get_me()), parse_mode=»html»)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
C:Users79065DesktopTupaModerationBotmain.py:82: RuntimeWarning: coroutine ‘Bot.send_message’ was never awaited
bot.send_message(int(needHelp[0]), «Support» + «: » + message.text[message.text.find(» «):])
RuntimeWarning: Enable tracemalloc to get the object allocation traceback

Ok. Warning, my main.py is still long.

import discord as d
from discord_webhook import DiscordWebhook
import sys, traceback
from discord.ext.commands import Bot
from discord.ext.commands import bot_has_permissions
from discord.ext.commands import has_permissions
from discord.ext import commands as c
import os
from random import randint
import sqlite3 as sql
import asyncio
from keep_alive import keep_alive

conn = sql.connect('Ratchet.db')
crsr = conn.cursor()

class MyClient(Bot):
	def __init__(self,*args,**kwargs):
		super().__init__(*args,**kwargs)
		
	async def on_ready(self):
		for cog in cogs:
			self.load_extension(cog)
		"""try:
			crsr.execute('DROP TABLE guilds;')
			conn.commit
		except sql.OperationalError:
			pass
		try:
			crsr.execute('DROP TABLE users;')
			conn.commit
		except sql.OperationalError:
			pass
		crsr.execute('CREATE TABLE guilds ( 
			guild_id UNSIGNED BIG integer NOT NULL, 
			prefix string 
		);')
		conn.commit
		for guild in self.guilds:
			crsr.execute('INSERT INTO guilds (guild_id, prefix) VALUES (?, ?)', (guild.id, '\'))
			conn.commit
		crsr.execute('UPDATE guilds SET prefix=? WHERE guild_id=?',('&',550722337050198036))
		crsr.execute('CREATE TABLE users ( 
			guild_id UNSIGNED BIG INT, 
			user_id UNSIGNED BIG INT, 
			xp INT 
		);')
		conn.commit()"""
		print('Logged in as')
		print('{0.user}'.format(self))
		print('Serving', end=' ')
		print('{} server(s)'.format(len(self.guilds)))

		while not self.is_closed():
			await self.change_presence(activity=d.Activity(type=d.ActivityType.watching, name='\help'))
			await asyncio.sleep(5)
			await self.change_presence(activity=d.Activity(type=d.ActivityType.watching, name=f'{len(self.guilds)} servers'))
			await asyncio.sleep(5)
		
	async def on_message(self,message):
		if not message.author.bot:
			try:
				crsr.execute('SELECT xp FROM users WHERE guild_id=? AND user_id=?', (message.guild.id, message.author.id))
				idk = crsr.fetchone()
				#await message.channel.send(idk)
				if idk is None: #user not ranked
					crsr.execute('INSERT INTO users (guild_id, user_id, xp) VALUES (?, ?, ?)', (message.guild.id, message.author.id, 1))
				else:
					crsr.execute('UPDATE users SET xp=? WHERE guild_id=? AND user_id=?', ((idk[0] or 0) + 1, message.guild.id, message.author.id))
				conn.commit()
			except AttributeError:
				pass
		await self.process_commands(message)		

def get_prefix(bot,msg):
	try:
		crsr.execute('SELECT prefix FROM guilds WHERE guild_id=?',(msg.guild.id,))
		idk = crsr.fetchone()
		if idk is None or idk[0] is None:
			return '\'
		return (idk[0], '\')
		crsr.commit()
	except AttributeError:
		return ['&','\']

client = MyClient(command_prefix=get_prefix)

client.crsr = crsr
client.conn = conn

cogs = ['Bot','Moderation','Miscellaneous','Games','errorhandler','owner']

with open('Ratchet/login.txt') as f:
    token = f.readline().strip()

keep_alive()

try:
	client.loop.run_until_complete(client.start(token))
except KeyboardInterrupt:
	conn.close()
	client.loop.run_until_complete(client.logout())
finally:
	client.loop.close()
	conn.close()

Понравилась статья? Поделить с друзьями:
  • Runtime error program exe abnormal program termination
  • Runtimeerror cuda error no kernel image is available for execution on the device
  • Runtime error program c windows system32 regsvr32
  • Runtimeerror cuda error device side assert triggered google colab
  • Runtime error program c windows system32 atibtmon exe как исправить