我正在尝试一个接一个地运行两个命令。我的代码如下:
baking.bake()
print "baking completed"
我的目标是运行baking.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)
答案 0 :(得分:2)
您可以使用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."
答案 1 :(得分:1)
基本上你会使用threading
模块及其join
方法:
import threading
def print_hello():
for _ in range(3):
print 'Hello'
hello_thread = threading.Thread(target=print_hello)
hello_thread.start()
hello_thread.join()
print "We're done!"
此代码将打印:
您好
您好
您好
我们已经完成了!
所以在你的情况下你会创建一个线程:
bake_thread = threading.Thread(target=baking.bake)
然后只需start
线程,join
即可。