【问题标题】:Concurrent execution of two python methods两个python方法的并发执行
【发布时间】:2022-01-10 13:57:52
【问题描述】:

我正在创建一个脚本,该脚本根据某些输入向 discord 和 twitter 发布消息。我必须使用方法(在单独的 .py 文件中)、post_to_twitter 和 post_to_discord。我想要实现的是,即使另一个失败(例如,如果登录出现异常),这两个也会尝试执行。

这里是发布到discord的相关代码sn-p:

def post_to_discord(message, channel_name):
    client = discord.Client()

    @client.event
    async def on_ready():
        channel = # getting the right channel
        await channel.send(message)
        await client.close()

    client.run(discord_config.token)

这里是发布到 twitter 部分的 sn-p(从 try-except 块中删除):

def post_to_twitter(message):
    auth = tweepy.OAuthHandler(twitter_config.api_key, twitter_config.api_key_secret)
    auth.set_access_token(twitter_config.access_token, twitter_config.access_token_secret)
    api = tweepy.API(auth)
    api.update_status(message)

现在,这两个都可以单独工作,并且在从同一个方法同步调用时:

def main(message):
    post_discord.post_to_discord(message)
    post_tweet.post_to_twitter(message)

但是,我无法让它们同时工作(即,即使不和谐失败,也尝试在 Twitter 上发帖,反之亦然)。我已经尝试了几种不同的多线程和异步方法。 其中,我尝试了this 问题的解决方案。但收到错误No module named 'IPython'。当我省略 IPython 行,将方法更改为异步时,我收到此错误:RuntimeError: Cannot enter into task <ClientEventTask state=pending event=on_ready coro=<function post_to_discord.<locals>.on_ready at 0x7f0ee33e9550>> while another task <Task pending name='Task-1' coro=<main() running at post_main.py:31>> is being executed.

说实话,我什至不确定 asyncio 是否适合我的用例,因此非常感谢任何见解。 谢谢。

【问题讨论】:

  • 你搜索过Python多线程入门/教程吗?您还可以考虑使用 Python 的异步方法。无论如何,这两件事是相似的,但不要一开始就将它们混合在一起,你只会比单独的任何一个主题更复杂。有关上下文,请同时使用tour 并阅读How to Ask

标签: python multithreading asynchronous concurrency python-asyncio


【解决方案1】:

在这种情况下,在完全独立的线程(和完全独立的事件循环)中运行这两个东西可能是您的专业水平最简单的选择。例如,试试这个:

import post_to_discord, post_to_twitter
import concurrent.futures

def main(message):
    with concurrent.futures.ThreadPoolExecutor() as pool:
        fut1 = pool.submit(post_discord.post_to_discord, message)
        fut2 = pool.submit(post_tweet.post_to_twitter, message)
    # here closing the threadpool will wait for both futures to complete

    # make exceptions visible
    for fut in (fut1, fut2):
        try:
            fut.result()
        except Exception as e:
            print("error: ", e)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-15
    • 2014-04-02
    • 2014-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多