title: Python multiprocessing: How to close the multiprocessing pool on exception
body: <p>I am using python multiprocessing to split one of the longer processes and run parallelly. It is working fine except when there is an exception in one of the child processes, in which case, process pool is not closed and I can still see those processes on the server. </p>
  
  <p>Here is the code: </p>
  
  <pre><code>from multiprocessing import Pool
  pool = Pool(processes=4)
  from functools import partial
  param_data = "Test Value"
  func = partial(test_function, param_data)
  r = pool.map(func, range(3))
  pool.close()
  
  def test_function(param_data,index):
     try:
        # The process here;
     except Exception as e:
        # Close the process pool;
  </code></pre>
  
  <p>On giving <code>pool.close</code> inside the except block it says </p>
  
  <blockquote>
    <p>NameError: global name 'pool' is not defined</p>
  </blockquote>
  
  <p>I tried to kill the process on Exception with the following code.</p>
  
  <pre><code>    except Exception as e:
         import os
         import signal
         pid = os.getpid()
         os.kill(pid, signal.SIGTERM) 
  </code></pre>
  
  <p>But I can still see the process on the server. This still not the best solution as this will only terminate the child process which encountered an exception other processes will still go on.</p>
  
  <p>I want all processes to terminate on completion, irrespective of if they encounter with an exception or not. </p>
  
  <p>I am running Python2.7</p>
  
  <p>Ps: I cannot install a new library like <a href="https://pypi.python.org/pypi/psutil" rel="noreferrer">psutil</a> on the server, I am trying for a solution using standard python library. </p>
  
  <p>I checked few similar questions such as, <a href="https://stackoverflow.com/questions/22784890/auto-kill-process-and-child-process-of-multiprocessing-pool" title="auto-kill-process-and-child">auto kill process and child</a> in this forum but they were not really this issue.</p>