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
Issue
Trying to use a semaphore to control asynchronous requests to control the requests to my target host but I am getting the following error which I have assume means that my asycio.sleep()
is not actually sleeping. How can I fix this? I want to add a delay to my requests for each URL targeted.
Error:
RuntimeWarning: coroutine 'sleep' was never awaited
Coroutine created at (most recent call last)
File "sephora_scraper.py", line 71, in <module>
loop.run_until_complete(main())
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/asyncio/base_events.py", line 571, in run_until_complete
self.run_forever()
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/asyncio/base_events.py", line 539, in run_forever
self._run_once()
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/asyncio/base_events.py", line 1767, in _run_once
handle._run()
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/asyncio/events.py", line 88, in _run
self._context.run(self._callback, *self._args)
File "makeup.py", line 26, in get_html
asyncio.sleep(delay)
asyncio.sleep(delay)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Code:
import sys
import time
import asyncio
import aiohttp
async def get_html(semaphore, session, url, delay=6):
await semaphore.acquire()
async with session.get(url) as res:
html = await res.text()
asyncio.sleep(delay)
semaphore.release()
return html
async def main():
categories = {
"makeup": "https://www.sephora.com/shop/"
}
semaphore = asyncio.Semaphore(value=1)
tasks = []
async with aiohttp.ClientSession(loop=loop, connector=aiohttp.TCPConnector(ssl=False)) as session:
for category, url in categories.items():
# Get HTML of all pages
tasks.append(get_html(semaphore, session, url))
res = await asyncio.gather(*tasks)
if __name__ == "__main__":
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
Solution
asyncio.sleep(delay)
Change it to:
await asyncio.sleep(delay)
asyncio.sleep
is a coroutine and should be awaited.
Answered By — Mikhail Gerasimov
Dr. Bacon,
D:projectLeocommandsocnovnoe.py:477: RuntimeWarning: coroutine 'Client.user_vk_request' was never awaited
c = await self.bot.user_vk_request('photos.saveMessagesPhoto', photo=b['photo'], server=['server'], hash=b['hash'])[0]
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Ignoring exception in command тест:
Traceback (most recent call last):
File "D:projectLeovenvlibsite-packagesvk_bottingcommands.py", line 62, in wrapped
ret = await coro(*args, **kwargs)
File "D:projectLeocommandsocnovnoe.py", line 477, in photo
c = await self.bot.user_vk_request('photos.saveMessagesPhoto', photo=b['photo'], server=['server'], hash=b['hash'])[0]
TypeError: 'coroutine' object is not subscriptable
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "D:projectLeovenvlibsite-packagesvk_bottingbot.py", line 820, in invoke
await ctx.command.invoke(ctx)
File "D:projectLeovenvlibsite-packagesvk_bottingcommands.py", line 845, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "D:projectLeovenvlibsite-packagesvk_bottingcommands.py", line 71, in wrapped
raise CommandInvokeError(exc) from exc
vk_botting.exceptions.CommandInvokeError: Command raised an exception: TypeError: 'coroutine' object is not subscriptable
{'server': 850720, 'photo': '[{"markers_restarted":true,"photo":"24232fd0cd:z","sizes":[],"latitude":0,"longitude":0,"kid":"623ea9c1fcf5c092c09e5bb30b24078e","sizes2":[["s","bb0bb5f84ecc74c27077b24a44f96b78a38688913d61151ac2eecd57","-8948426774666194859",75,47],["m","4e95d4a2493760f6102b96971f4f4d4ba28afd1d40d4bc08ccb22cdc","7424489279040516911",130,81],["x","ca6185c19d3076e7ca098f0eae074fd3ed5ecf76a257edcf985e4188","5666038782456437582",604,377],["y","ab34df9a24cf4124603034ab3c1dc17300622bc46752f7c58bcee25c","-7319436552321038215",807,504],["z","7af0d30141f64ebe2fe8c9dba87095de83b20d5e3518eaf7be5de4ea","-4524142561723001457",1280,800],["o","5bc5eb8e9537f3fba845c2ea3c7f41bd399efaa87a69639e0563aa3d","6302533467391289737",130,87],["p","67fe7e6fe6f6c501784401e6869a7dc3e1e1532ed997c30172f8033b","7407183215490552013",200,133],["q","15664df899bf20ddcabdd6812cf139f8432e1ca52818916b4c628783","5039433027754640290",320,213],["r","b61ee303e6f64da7a7134ba3300c682407ca742199f8119444f101e4","5499859000876225307",510,340]],"urls":[],"urls2":["uwu1-E7MdMJwd7JKRPlreKOGiJE9YRUawu7NVw/VVBtXULN0IM.jpg","TpXUokk3YPYQK5aXH09NS6KK_R1A1LwIzLIs3A/L_Pno6kVCWc.jpg","ymGFwZ0wdufKCY8OrgdP0-1ez3aiV-3PmF5BiA/Thvnr0DQoU4.jpg","qzTfmiTPQSRgMDSrPB3BcwBiK8RnUvfFi87iXA/eQjlVjwjbJo.jpg","evDTAUH2Tr4v6MnbqHCV3oOyDV41GOr3vl3k6g/j1VGX08EN8E.jpg","W8XrjpU38_uoRcLqPH9BvTme-qh6aWOeBWOqPQ/iWne3MsYd1c.jpg","Z_5-b-b2xQF4RAHmhpp9w-HhUy7Zl8MBcvgDOw/zdCMueOZy2Y.jpg","FWZN-Jm_IN3KvdaBLPE5-EMuHKUoGJFrTGKHgw/osOvgKOp70U.jpg","th7jA-b2TaenE0ujMAxoJAfKdCGZ-BGURPEB5A/G1P2LZ9sU0w.jpg"]}]', 'hash': '73c948aa00927170bcc05a37da09bc6a'}
Got exception in request:
Retrying in 1 seconds
У меня код нормально вставлен, эта на сайте таб упал
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()