如何在python中一个接一个地运行两个进程

我正在尝试运行两个命令,一个接一个.我的代码如下:

baking.bake()
print "baking completed"

我的目标是运行akeing.bake()(大约需要1分钟才能完成),此后立即要打印“开始烘焙”.最后,烘烤完成后,我要打印“烘烤完成”.本质上:如何异步运行bake()?

这是我的backing.py文件

# Bake a texture map
from cgkit.cmds import load, worldObject, listWorld
from cgkit.rmshader import RMMaterial, RMShader
from cgkit.sceneglobals import Globals



def bake():
        Globals(
            bake = True,
            resolution = (512, 512),
            pixelsamples = (2,2),
            output = "ao_map.tif",
            displaymode = "rgba"
        )

        # Load the model
        load("singleSofa.obj")
        # Obtain a reference to the model
        model = worldObject("small_sofa_dark_grey")

        # Set the bake material
        mat = RMMaterial(
            surface = RMShader(
                "bake_ao.sl",
                samples = 1000,
            )
        )

        model.setMaterial(mat)

解决方法:

您可以使用multiprocessing module,如下所示:

from multiprocessing import Pool
import time

def something(i):
    time.sleep(2)
    return i+i

pool = Pool(processes=1)
res = pool.apply_async(something, [2])
print "Started something, waiting..."
# ...
print "Done with something. Result was: %s" % (res.get())

因此,在您的情况下,我们可以执行以下操作:

from multiprocessing import Pool

# Create baking object and so forth.
# ...

pool = Pool(processes=1)
res = pool.apply_async(baking.bake)
print "Baking started"

# Then we do something while we wait...

res.get()
print "Baking done."
上一篇:Python Socket和Thread池,如何获得更多性能?


下一篇:Python:在不同过程中将Pool对象传递给函数