后台Python函数

2024-10-03 17:14:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我想独立运行一个函数。从我调用的函数中,我希望返回而不等待其他函数结束。在

我试过用threadind,但这会等着,结束。在

thread = threading.Thread(target=myFunc)
thread.daemon = True
thread.start()
return 'something'

是否可以立即返回而另一个进程仍在运行? 谢谢你的回答。在

已编辑 工作代码如下:

^{pr2}$

Tags: 函数代码true编辑targetreturn进程myfunc
3条回答

我认为您使用的语法是正确的,我不明白为什么您的请求不应该立即返回。你有没有验证过这个请求实际上挂起直到线程结束?在

我建议将myFunc设置为写入一个文件以便您跟踪它

def myFunc():
    f = open('file.txt', 'w')
    while True:
        f.write('hello world')

如果我正确地理解了您的请求,您可能需要查看一下工作队列 https://www.djangopackages.com/grids/g/workers-queues-tasks/

基本上,将工作卸载到视图中创建的线程不是一个好主意,这通常是通过拥有一个后台工作线程池(进程、线程)和传入请求队列来处理的。在

你或多或少在问以下问题:

Is it possible to run function in a subprocess without threading or writing a separate file/script

您必须像这样更改链接中的示例代码:

from multiprocessing import Process

def myFunc():
    pass  # whatever function you like

p = Process(target=myFunc)
p.start()  # start execution of myFunc() asychronously
print)'something')

p.start()是异步执行的,即“something”会立即打印出来,不管myFunc()的执行有多耗时。脚本执行myFunc(),而不等待它完成。在

相关问题 更多 >