gevent.spawn 获取返回值
时间: 2023-09-26 07:08:01 浏览: 48
gevent.spawn 函数是异步调用的,不会立即获得返回值。如果需要等待协程执行完毕并返回结果,可以使用 gevent.spawn().get() 方法,该方法会阻塞当前协程,直到被调用协程执行完毕并返回结果。例如:
```python
import gevent
def my_func():
return 'Hello, world!'
# 创建并执行协程
task = gevent.spawn(my_func)
# 阻塞当前协程,等待协程执行完毕并返回结果
result = task.get()
print(result)
```
以上代码会输出 "Hello, world!",即协程执行的结果。
相关问题
python 的gevent.spawn获取所有协程的返回值
可以使用 gevent.joinall() 函数来等待所有协程执行完毕,并且获取它们的返回值。例如:
```python
import gevent
def task1():
return "hello"
def task2():
return "world"
gevent.joinall([gevent.spawn(task1), gevent.spawn(task2)])
results = [greenlet.value for greenlet in gevent.getcurrent().greenlet.getchildren()]
print(results) # Output: ['hello', 'world']
```
在这个例子中,我们定义了两个函数 task1 和 task2,分别返回字符串 "hello" 和 "world"。然后,我们使用 gevent.spawn() 函数异步执行这两个函数,并且使用 gevent.joinall() 等待它们执行完毕。最后,我们通过遍历当前的 greenlet 的子 greenlet,获取所有协程的返回值,并且打印输出。
gevent.joinall([gevent.spawn()])是什么意思
gevent.joinall([gevent.spawn()])是一个使用gevent库的函数调用。它的作用是等待所有传入的gevent.spawn()协程执行完毕后再继续执行下面的代码。
gevent.spawn()是一个用于创建和启动协程的函数。它接受一个可调用对象作为参数,并返回一个gevent.Greenlet对象,代表一个协程。在这个函数调用中,可能会有多个gevent.spawn()协程被创建。
gevent.joinall()函数接受一个协程对象列表作为参数,用于等待这些协程执行完毕。它会阻塞当前线程,直到所有传入的协程都执行完毕。
因此,gevent.joinall([gevent.spawn()])的意思是创建并启动一个协程,然后等待该协程执行完毕,再继续执行下面的代码。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)