简体   繁体   English

如何不等功能完成python

[英]How to not wait for function to finish python

I'm trying to program a loop with a asynchronous part in it. 我正在尝试编写一个带有异步部分的循环。 I dont want to wait for this asynchronous part every iteration though. 我不想每次迭代都等待这个异步部分。 Is there a way to not wait for this function inside the loop to finish? 有没有办法不等待循环内的这个功能完成?

In code (example): 在代码中(示例):

import time
def test():
    global a
    time.sleep(1)
    a += 1
    test()

global a
a = 10
test() 
while(1):
    print a

Thanks in advance! 提前致谢!

You can put it in a thread. 你可以把它放在一个线程中。 Instead of test() 而不是test()

from threading import Thread
Thread(target=test).start()
print("this will be printed immediately")

A simple way is to run test() in another thread 一种简单的方法是在另一个线程中运行test()

import threading

th = threading.Thread(target=test)
th.start()

You should look at a library meant for asynchronous requests, such as gevent 您应该查看用于异步请求的库,例如gevent

Examples here: http://sdiehl.github.io/gevent-tutorial/#synchronous-asynchronous-execution 这里的示例: http//sdiehl.github.io/gevent-tutorial/#synchronous-asynchronous-execution

import gevent

def foo():
    print('Running in foo')
    gevent.sleep(0)
    print('Explicit context switch to foo again')

def bar():
    print('Explicit context to bar')
    gevent.sleep(0)
    print('Implicit context switch back to bar')

gevent.joinall([
    gevent.spawn(foo),
    gevent.spawn(bar),
])

use thread . 使用thread it creates a new thread in that the asynchronous function runs 它创建了一个新的线程,因为异步函数运行

https://www.tutorialspoint.com/python/python_multithreading.htm https://www.tutorialspoint.com/python/python_multithreading.htm

To expand on blue_note, let's say you have a function with arguments: 要扩展blue_note,假设你有一个带参数的函数:

def test(b):
    global a
    time.sleep(1)
    a += 1 + b

You need to pass in your args like this: 你需要像这样传递你的args:

from threading import Thread
b = 1
Thread(target=test, args=(b, )).start()
print("this will be printed immediately")

Note args must be a tuple. 注意args必须是一个元组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM