IMP logo
IMP Reference Guide  2.21.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 
28 if sys.platform == 'win32':
29  def _run_background(cmdline, out):
30  """Run a process in the background and direct its output to a file"""
31  print("%s > %s" % (cmdline, out))
32  try:
33  # shell isn't needed on Win32, and may not be found under wine
34  # anyway
35  _ = subprocess.Popen(cmdline, shell=False, stdout=open(out, 'w'),
36  stderr=subprocess.STDOUT,
37  universal_newlines=True)
38  # Ignore Windows "file not found" errors, so that behavior is
39  # consistent between Unix and Windows
40  except WindowsError as detail:
41  print(("WindowsError: %s (ignored)" % detail))
42 
43 else:
44 
45  def _run_background(cmdline, out):
46  """Run a process in the background and direct its output to a file"""
47  print("%s > %s" % (cmdline, out))
48  subprocess.Popen(cmdline, shell=True, stdout=open(out, 'w'),
49  stderr=subprocess.STDOUT,
50  universal_newlines=True)