如何在Python中顺序运行两个进程
我想要依次运行两个命令。我的代码是这样的:
baking.bake()
print "baking completed"
我的目标是先运行 baking.bake()
(这个过程大约需要1分钟),然后立刻打印“baking started”。最后,当烘焙完成后,我想打印“baking done”。简单来说,我想知道如何异步运行 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)
2 个回答
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
。
2
你可以使用 multiprocessing模块,像下面这样:
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."