RError.com

RError.com Logo RError.com Logo

RError.com Navigation

  • 主页

Mobile menu

Close
  • 主页
  • 系统&网络
    • 热门问题
    • 最新问题
    • 标签
  • Ubuntu
    • 热门问题
    • 最新问题
    • 标签
  • 帮助
主页 / 问题

问题[asyncio]

Martin Hope
Sam Knight
Asked: 2022-07-30 22:23:01 +0000 UTC

错误 asyncio 任务被破坏,但它正在等待处理!

  • 0

请帮我找出问题所在。这是可执行代码:

import pandas as pd
import sqlalchemy
from binance.client import Client
from binance import BinanceSocketManager
import asyncio

client = Client(api_key, api_secret)

async def main():

    bsm = BinanceSocketManager(client)
    socket = bsm.trade_socket('BTCUSDT')
    await socket.__aenter__()
    msg = await socket.recv()
    return print(msg)

loop = asyncio.get_event_loop()
forecast = loop.run_until_complete(main())
loop.close()

错误:任务已销毁,但它正在等待处理!任务:<Task pending name='Task-9' coro=<WebSocketCommonProtocol.recv() 完成,定义在 /Users/v/Downloads/soft/anaconda3/lib/python3.9/site-packages/websockets/legacy/protocol .py:486> wait_for=<Future pending cb=[<TaskWakeupMethWrapper object at 0x7fd45d952a90>()]> cb=[_release_waiter(()]>)() at /Users/v/Downloads/soft/anaconda3/lib/python3 .9/asyncio/tasks.py:416]>

python asyncio
  • 1 个回答
  • 75 Views
Martin Hope
krubsburger
Asked: 2022-07-30 00:33:10 +0000 UTC

如何使python asyncio全局变量无效?

  • 1

我正在编写一个个人电报机器人来收集我的market.csgo.com帐户的统计数据。该机器人的主要任务是向 API 发送异步请求并通过 Telegram 显示信息。一切正常,但问题在于全局变量,或者更确切地说,它们的计数不正确。我的功能之一的示例:

...
import asyncio
import aiohttp


sale_total_sum = 0
amount_total_items = 0

async def get_on_sale(session, dictt, message):
    global sale_total_sum
    global amount_total_items

    async with session.get(f'https://market.csgo.com/api/v2/items?key={dictt[1][1]}') as resp:
        html = await resp.json()
        
        if html['items'] is None:
            pass
        else:
            each_sale_sum = 0
            each_amount_items = 0
            
            for i in html['items']:
                sale_total_sum += i['price']
                each_sale_sum += i['price']
                each_amount_items += 1
                amount_total_items += 1
               
            try:
                await bot.send_message(message.from_user.id,
                    f'<a href="{dictt[1][0]}">{dictt[0]}</a> : <b>{each_sale_sum} ₽</b>\nItems: <i>{each_amount_items}</i>',
                    disable_web_page_preview=True, parse_mode=types.ParseMode.HTML)
            except exceptions.RetryAfter as e:
                await asyncio.sleep(e.timeout)


@dp.message_handler(content_types=['text'])
async def Main(message):
    profiles = users()
    
    async with aiohttp.ClientSession(trust_env=True) as session:
        tasks = []
        
        if message.text == 'On Sale 💰':
            await bot.send_message(message.from_user.id, 'Information request. Wait..')
           
            for i in profiles.items():
                task = asyncio.ensure_future(get_on_sale(session, i, message))
                tasks.append(task)
            await asyncio.gather(*tasks)
            
            await bot.send_message(message.from_user.id,
                f'<b>Total on sale: {sale_total_sum} ₽\nTotal items: {amount_total_items}\nBot start at: {start}</b>',
                reply_markup=kb_client, parse_mode=types.ParseMode.HTML)


executor.start_polling(dp, skip_updates=True)

函数结果:

Account_1: 100 ₽
Items: 1
Account_2: 200 ₽
Items: 2
Account_3: 300 ₽
Items: 3
Total on sale: 600 ₽
Total items: 6

该机器人在轮询模式下工作executor.start_polling(dp, skip_updates=True)。如果在包含后第一次调用该函数async def get_on_sale,那么它的最终计数Total on sale: 600 ₽ Total items: 6将是正确的,但随后的调用会使这个数量翻倍,实际上并非如此:

Account_1: 100 ₽
Items: 1
Account_2: 200 ₽
Items: 2
Account_3: 300 ₽
Items: 3
Total on sale: 1200 ₽
Total items: 12

我知道问题出在全局变量global sale_total_sum和global amount_total_items. 但是,如果您改用简单变量,它们将被简单地覆盖,而不是按照我的需要进行汇总。因此,我想问 -有没有办法在函数结束后以某种方式重置或重新分配这些全局变量为 0?这样在下一次调用时数据将是正确的。谢谢你。

python asyncio
  • 1 个回答
  • 49 Views
Martin Hope
Andrew Pristagin
Asked: 2022-08-16 19:44:46 +0000 UTC

并行运行多个永恒循环

  • 0

我有以下代码

from pyrogram import Client, filters
from settings import *

app = Client("my_account", api_id=api_id, api_hash=api_hash)

groups_id = {-1001694: 20, -1001786: 10}  # вместо настоящих айди фейковые


def send(app, id, time):
    while True:
        app.send_message(id, "test222")
        sleep(time)

with app:
    for id, time in groups_id.items():
        send(app, id, time)  # строка запуска

所以这里的问题是:如何多次运行发送,即 在“起跑线”之后,循环继续工作,就好像没有永恒的循环一样,但它实际上会起作用吗?我尝试了异步和并行但没有任何效果

这是异步版本:

from settings import *
import asyncio

app = Client("my_account", api_id=api_id, api_hash=api_hash)

groups_id = {-1001694: 20, -1001786: 10}  # вместо настоящих айди фейковые


async def send(app, id, time):
    while True:
        await app.send_message(id, "test222")
        await asyncio.sleep(time)

async def main():
    async with app:
        for id, time in groups_id.items():
            await send(app, id, time)  # строка запуска

asyncio.run(main())

但这里的结果是一样的,只发送给一组

更新:感谢此人的回复:insolor

这是最终代码:

from settings import *
import asyncio

app = Client("my_account", api_id=api_id, api_hash=api_hash)

groups_id = {-100169: 20, -1001729: 10}  # вместо настоящих айди фейковые


async def send(app, id, time):
    while True:
        await app.send_message(id, "test222")
        await asyncio.sleep(time)

async def main():
    async with app:
        await asyncio.gather(*[send(app, id, time) for id, time in groups_id.items()])

asyncio.run(main())
python asyncio
  • 1 个回答
  • 69 Views
Martin Hope
JleUTeHaHT
Asked: 2022-08-01 19:47:54 +0000 UTC

电视马拉松活动不起作用

  • 0
import pymysql, time, asyncio, requests, sys, threading, os, socks
from telethon import TelegramClient, events
from telethon.tl.functions.channels import JoinChannelRequest

pid = os.getpid()
print(pid)

r = requests.post('http://ip:5000/api/select/account', json={"token": ""})
if r.json()['Status'] == 2:
    print("Нет доступных аккаунтов")
    sys.exit()
else:
    x, Phone, Api_id, Api_hash = r.json()['Id'], r.json()['Phone'], r.json()['Api_id'], r.json()['Api_hash']

client = TelegramClient(session=str(f'C:\\Users\\Админ\\Desktop\\RG\\new\\session{x}'), api_id=Api_id, api_hash=Api_hash).start()

a = requests.post('http://ip:5000/api/set/status/pid', json={"token": "", "x": x, "pid": pid})

@client.on(events.NewMessage(func=lambda e: e.is_private))
async def handler(event):
    try:
        print(event.message.message)#текст
        await client.get_dialogs()
        id = event.message.peer_id.user_id#юзерка пользователя
        info = await client.get_entity(event.message.peer_id.user_id)
        print(info.to_dict()['username'])#юзерка
        username = info.to_dict()['username']
        if username is None:
            username = "None"
        z = requests.post('http://ip:5000/api/upload/message', json={"token": "", "x": x, "Text": event.message.message, "User_id": id, "Username": username, "Number": Phone, "id": x})
    except Exception as e:
        print(e)

async def join(Task, client):
    print("1")
    print(Task)
    return await client(JoinChannelRequest(Task))

async def send(Task, Message, client):
    print("2")
    print(Task, Message)
    return await client.send_message(f"{Task}", f"{Message}")

#/api/check/task/account
def t():
    while True:
        r = requests.post('http://ip:5000/api/check/task/account', json={"token": "", "Phone": Phone})
        if r.json()['status'] == 2:
            time.sleep(2)
        else:
            Type = r.json()['Type']
            if Type == "join":
                Task = r.json()['Task']
                _thread = threading.Thread(target=asyncio.run, args=(join(Task, client),)).start()
            if Type == "send":
                Task = r.json()['Task']
                Message = r.json()['Message']
                _thread = threading.Thread(target=asyncio.run, args=(send(Task, Message, client),)).start()

threading.Thread(target=t, args=()).start()

client.run_until_disconnected()

当向函数发送任务(加入、发送)时,它们根本不会被执行,尽管如果它不是以异步方式启动,一切正常。

asyncio
  • 1 个回答
  • 10 Views

Sidebar

Stats

  • 问题 10021
  • Answers 30001
  • 最佳答案 8000
  • 用户 6900
  • 常问
  • 回答
  • Marko Smith

    我看不懂措辞

    • 1 个回答
  • Marko Smith

    请求的模块“del”不提供名为“default”的导出

    • 3 个回答
  • Marko Smith

    "!+tab" 在 HTML 的 vs 代码中不起作用

    • 5 个回答
  • Marko Smith

    我正在尝试解决“猜词”的问题。Python

    • 2 个回答
  • Marko Smith

    可以使用哪些命令将当前指针移动到指定的提交而不更改工作目录中的文件?

    • 1 个回答
  • Marko Smith

    Python解析野莓

    • 1 个回答
  • Marko Smith

    问题:“警告:检查最新版本的 pip 时出错。”

    • 2 个回答
  • Marko Smith

    帮助编写一个用值填充变量的循环。解决这个问题

    • 2 个回答
  • Marko Smith

    尽管依赖数组为空,但在渲染上调用了 2 次 useEffect

    • 2 个回答
  • Marko Smith

    数据不通过 Telegram.WebApp.sendData 发送

    • 1 个回答
  • Martin Hope
    Alexandr_TT 2020年新年大赛! 2020-12-20 18:20:21 +0000 UTC
  • Martin Hope
    Alexandr_TT 圣诞树动画 2020-12-23 00:38:08 +0000 UTC
  • Martin Hope
    Air 究竟是什么标识了网站访问者? 2020-11-03 15:49:20 +0000 UTC
  • Martin Hope
    Qwertiy 号码显示 9223372036854775807 2020-07-11 18:16:49 +0000 UTC
  • Martin Hope
    user216109 如何为黑客设下陷阱,或充分击退攻击? 2020-05-10 02:22:52 +0000 UTC
  • Martin Hope
    Qwertiy 并变成3个无穷大 2020-11-06 07:15:57 +0000 UTC
  • Martin Hope
    koks_rs 什么是样板代码? 2020-10-27 15:43:19 +0000 UTC
  • Martin Hope
    Sirop4ik 向 git 提交发布的正确方法是什么? 2020-10-05 00:02:00 +0000 UTC
  • Martin Hope
    faoxis 为什么在这么多示例中函数都称为 foo? 2020-08-15 04:42:49 +0000 UTC
  • Martin Hope
    Pavel Mayorov 如何从事件或回调函数中返回值?或者至少等他们完成。 2020-08-11 16:49:28 +0000 UTC

热门标签

javascript python java php c# c++ html android jquery mysql

Explore

  • 主页
  • 问题
    • 热门问题
    • 最新问题
  • 标签
  • 帮助

Footer

RError.com

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

帮助

© 2023 RError.com All Rights Reserve   沪ICP备12040472号-5