Skip to content

ENH: Interfaces with automated population of outputs #3150

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 3 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
enh: capture standard err/out
  • Loading branch information
oesteban committed Jan 8, 2020
commit 2f4ac09cd4e02856798c20dd5a29cb11d2b4c6ac
68 changes: 67 additions & 1 deletion nipype/interfaces/base/experimental.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
"""Experimental Nipype 1.99 interfaces."""
import os
import sys
import platform
import json
from io import StringIO
from string import Formatter
from contextlib import AbstractContextManager
from copy import deepcopy
from datetime import datetime as dt
from dateutil.parser import parse as parseutc
Expand Down Expand Up @@ -275,9 +278,12 @@ def run(self, cwd=None, ignore_exception=None, **inputs):

# Grab inputs now, as they should not change during execution
inputs = self.inputs.get_traitsfree()
stdout = StringIO()
stderr = StringIO()
try:
runtime = self._pre_run_hook(runtime)
runtime = self._run_interface(runtime)
with RedirectStandardStreams(stdout, stderr=stderr):
runtime = self._run_interface(runtime)
runtime = self._post_run_hook(runtime)
except Exception as e:
import traceback
Expand All @@ -295,6 +301,8 @@ def run(self, cwd=None, ignore_exception=None, **inputs):

runtime.traceback_args = ("\n".join(["%s" % arg for arg in exc_args]),)

stderr.write("Nipype captured error:\n\n%s" % runtime.traceback)

if not ignore_exception:
raise
finally:
Expand All @@ -303,6 +311,7 @@ def run(self, cwd=None, ignore_exception=None, **inputs):
"{} interface failed to return valid "
"runtime object".format(interface.__class__.__name__)
)

# This needs to be done always
runtime.endTime = dt.isoformat(dt.utcnow())
timediff = parseutc(runtime.endTime) - parseutc(runtime.startTime)
Expand Down Expand Up @@ -342,6 +351,10 @@ def run(self, cwd=None, ignore_exception=None, **inputs):
}
results.runtime = runtime

# Store captured outputs
runtime.stdout = stdout.getvalue()
runtime.stderr = stderr.getvalue()

results.outputs = self._find_outputs(runtime)
os.chdir(syscwd)

Expand Down Expand Up @@ -454,3 +467,56 @@ def _find_outputs(self, runtime):
setattr(outputs, name,
''.join((out_template.format(**fields), ext)))
return outputs


class RedirectStandardStreams(AbstractContextManager):
"""
Context that redirects standard out/err.

Examples
--------
>>> f = StringIO()
>>> with RedirectStandardStreams(f):
... print("1")
... print("2", file=sys.stderr)
>>> captured = f.getvalue()
>>> "1" in captured
True
>>> "2" in captured
True

>>> out = StringIO()
>>> err = StringIO()
>>> with RedirectStandardStreams(out, err):
... print("1")
... print("2", file=sys.stderr)
>>> captured_out = out.getvalue()
>>> "1" in captured_out
True
>>> "2" in captured_out
False
>>> captured_err = err.getvalue()
>>> "1" in captured_err
False
>>> "2" in captured_err
True

"""

_defaults = (sys.stdout, sys.stderr)

def __init__(self, stdout, stderr=None):
"""Redirect standard streams."""
self._out_target = stdout
self._err_target = stderr

def __enter__(self):
sys.stdout = self._out_target
sys.stderr = self._err_target
if self._err_target is None:
sys.stderr = self._out_target
return self._out_target
return self._out_target, self._err_target

def __exit__(self, exctype, excinst, exctb):
sys.stdout, sys.stderr = self._defaults
5 changes: 3 additions & 2 deletions nipype/interfaces/base/tests/test_experimental.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""Proof of concept."""
import sys
from ....utils.filemanip import fname_presuffix
from ... import base as nib
from ..experimental import AutoOutputInterface
Expand Down Expand Up @@ -45,8 +46,8 @@ class TestInterface(AutoOutputInterface):
output_spec = _OutputSpec

def _run_interface(self, runtime):
runtime.stdout = _TOOL_OUTPUT
runtime.stderr = ' '.join(('a', 'b', '1', '2', '3.0'))
print(_TOOL_OUTPUT)
print(' '.join(('a', 'b', '1', '2', '3.0')), file=sys.stderr)
out_fname = fname_presuffix(
self.inputs.woo, suffix='_brain')
open(out_fname, 'w').close()
Expand Down