gpt4 book ai didi

Python创建一个子进程并且不等待

转载 作者:太空宇宙 更新时间:2023-11-04 08:00:14 26 4
gpt4 key购买 nike

我想运行一系列命令(需要很长时间)。但我不想等待每个命令完成。我如何在 Python 中解决这个问题?

我看了

os.fork()

subprocess.popen()

别以为那是我需要的。

代码

def command1():
wait(10)

def command2():
wait(10)

def command3():
wait(10)

我想打电话

command1()
command2()
command3()

无需等待。

最佳答案

使用 python 的多处理模块。

def func(arg1):
... do something ...

from multiprocessing import Process
p = Process(target=func, args=(arg1,), name='func')
p.start()

完整的文档在这里:https://docs.python.org/2/library/multiprocessing.html

编辑:

如果您使用的是 jpython/cpython 发行版,您还可以使用 python 的线程模块,因为您可以克服这些发行版中的 GIL(全局解释器锁)。

https://docs.python.org/2/library/threading.html

关于Python创建一个子进程并且不等待,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41504942/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com