如果停止函数中的运行状态为“停止”,我想在上传函数中引发异常。这似乎不起作用。我正在使用 Pipe 来传递异常。怎么了?
def upload(instances, u1):
for instance in instance:
try:
u1.recv()
#do_something
except:
#do_something_else
continue
def stop(instances, s1):
for instance in instances:
RunningStatus = instance[4]
if RunningStatus.lower() == 'stopped'.lower():
s1.send(Exception) # I want to raise exception in upload function
# from here
if __name__ == '__main__':
s1, u1 = multiprocessing.Pipe()
s = multiprocessing.Process(target = stop, args = (instances, s1,))
u = multiprocessing.Process(target = upload, args = (instances, u1))
s.start()
u.start()
u.join()
下面是如何将 Exception 对象从一个进程发送到另一个进程的示例。我还尝试发送完整的异常信息(由 sys.exc_info 返回),但是,合理地说,这失败了。人们总是可以将回溯信息格式化为字符串并发送(请参阅回溯模块)。
在 Ubuntu 14.04 Python 2.7、3.4(Ubuntu 提供)和 3.5(Continuum)上进行了测试。
from __future__ import print_function
import sys
import multiprocessing
import time
def upload(u1):
i=0
try:
while True:
print('>upload>',i)
i+=1
if u1.poll():
# tvt = u1.recv()
# raise tvt[0], tvt[1], tvt[2] # Python 2.7
e = u1.recv()
raise e
time.sleep(0.1)
except Exception as e:
print('Exception caught:',e)
print('exiting')
def stop(s1):
try:
while True:
for j in range(100,110):
time.sleep(0.1)
if 105==j:
raise RuntimeError("oh dear at j={}".format(j))
except Exception as e:
# tvt = sys.exc_info()
# s1.send(tvt) # doesn't work; tracebacks are not pickle'able
s1.send(e)
if __name__ == '__main__':
s1, u1 = multiprocessing.Pipe()
s = multiprocessing.Process(target = stop, args = (s1,))
u = multiprocessing.Process(target = upload, args = (u1,))
s.start()
u.start()
u.join()
Output:
>upload> 0
>upload> 1
>upload> 2
>upload> 3
>upload> 4
>upload> 5
>upload> 6
Exception caught: oh dear at j=105
exiting
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)