How can I cancel one asyncio task from another in Python?

0
6
Asked By CreativeSparrow92 On

I'm trying to figure out how to cancel task1 from within task2 using Python's asyncio module. I attempted to call t1.cancel(), but it doesn't seem to stop task1 from executing. I found out that the global variable t1 isn't accessible inside the async function task1. So, I believe I need to pass it as an argument to task2. Can anyone help clarify this?

2 Answers

Answered By AsyncGuru93 On

To manage multiple tasks effectively, it's crucial to understand variable scope in Python. Make sure you're using global variables correctly, and consider passing them directly as parameters to avoid any confusion. Keep experimenting and you'll get the hang of it!

Answered By CodeNinjaX On

It looks like you haven't properly assigned the global variables in your code. When you set t1 and t2 in the main function, those are scoped to main only. To modify the global t1 and t2, you need to declare them as global inside your main function. Just add `global t1, t2` at the start of main, and initialize them with `t1, t2 = None, None` at the top of your file. That should do the trick! Check out this link for more guidance: realpython.com/python-use-global-variable-in-function/

Pythonista101 -

Yes, it is working now.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.