【发布时间】: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