【发布时间】:2014-09-11 14:35:10
【问题描述】:
在我的脚本运行时,可能会在某些时候发生错误。在这种情况下,应正确终止所有进程,返回错误消息,并退出脚本。
我现在的代码似乎还不能满足这些要求。发生错误时,将其发送到report_error(),脚本最终挂在终端中,活动监视器显示许多 Python 进程仍在运行。
环境
- Mac OS X 10.8.5
- Python 3.3.3
从脚本中的任何一点终止所有进程的正确方法是什么?
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
from multiprocessing import Pool
# Global variables.
input_files = [
'test_data_0.csv',
'test_data_1.csv'
]
def report_error(error):
# Reports errors then exits script.
print("Error: {0}".format(error), file=sys.stderr)
sys.exit(1)
# What I really want is to report the error, properly terminate all processes,
# and then exit the script.
def read_file(file):
try:
# Read file into list.
except Exception as error:
report_error(error)
def check_file(file):
# Do some error checking on file.
if error:
report_error(error)
def job(file):
# Executed on each item in input_files.
check_file(file)
read_file(file)
def main():
# Sets up a process pool. Defaults to number of cores.
# Each input gets passed to job and processed in a separate process.
p = Pool()
p.map(job, input_files)
# Closing and joining a pool is important to ensure all resources are freed properly.
p.close()
p.join()
if __name__ == '__main__':
main()
【问题讨论】:
-
澄清一下,您希望其中一名工作人员发生错误导致所有其他工作人员和父进程终止?
-
另外,你关心
job返回什么值吗?如果是这样,您是否关心返回结果的顺序?
标签: python python-3.x multiprocessing