IMP logo
IMP Reference Guide  2.5.0
The Integrative Modeling Platform
subproc.py
1 """@namespace IMP.parallel.subproc Subprocess handling."""
2 
3 from __future__ import print_function
4 import sys
5 import subprocess
6 
7 
8 class _Popen4(subprocess.Popen):
9 
10  """Utility class to provide a portable way to spawn a child process and
11  communicate with its stdin and combined stdout/stderr."""
12 
13  def __init__(self, cmd):
14  # shell isn't needed on Win32, and may not be found under wine anyway
15  shell = (sys.platform != "win32")
16  subprocess.Popen.__init__(
17  self, cmd, shell=shell, stdin=subprocess.PIPE,
18  stdout=subprocess.PIPE,
19  stderr=subprocess.STDOUT, universal_newlines=True)
20 
21  def require_clean_exit(self):
22  """Make sure the child exited with a zero return code"""
23  r = self.wait()
24  if r != 0:
25  raise IOError("Process failed with exit status %d" % r)
26 
27 if sys.platform == 'win32':
28  def _run_background(cmdline, out):
29  """Run a process in the background and direct its output to a file"""
30  print("%s > %s" % (cmdline, out))
31  try:
32  # shell isn't needed on Win32, and may not be found under wine
33  # anyway
34  p = subprocess.Popen(cmdline, shell=False, stdout=open(out, 'w'),
35  stderr=subprocess.STDOUT,
36  universal_newlines=True)
37  # Ignore Windows "file not found" errors, so that behavior is consistent
38  # between Unix and Windows
39  except WindowsError as detail:
40  print(("WindowsError: %s (ignored)" % detail))
41 
42 else:
43 
44  def _run_background(cmdline, out):
45  """Run a process in the background and direct its output to a file"""
46  print("%s > %s" % (cmdline, out))
47  subprocess.Popen(cmdline, shell=True, stdout=open(out, 'w'),
48  stderr=subprocess.STDOUT,
49  universal_newlines=True)