From 448ac8584d2b8cfeab7a9412f8966d88d8d99d14 Mon Sep 17 00:00:00 2001 From: Martin Craig <martin.craig@eng.ox.ac.uk> Date: Wed, 31 Oct 2018 12:43:09 +0000 Subject: [PATCH] Added fileOrText decorator to enable text input/output to be read/output as Python strings This is helpful for scripts which write out a logfile for example --- fsl/wrappers/wrapperutils.py | 40 ++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/fsl/wrappers/wrapperutils.py b/fsl/wrappers/wrapperutils.py index 40ecfd1f7..2ddf3f00e 100644 --- a/fsl/wrappers/wrapperutils.py +++ b/fsl/wrappers/wrapperutils.py @@ -1005,3 +1005,43 @@ def fileOrArray(*args, **kwargs): return _update_wrapper(wrapper, func) return decorator + +def fileOrText(*args, **kwargs): + """Decorator which can be used to ensure that any text output (e.g. log file are saved + to text files, and output files can be loaded and returned as strings. + """ + + def prepIn(workdir, name, val): + + infile = None + + if isinstance(val, six.string_types): + with tempfile.NamedTemporaryFile(mode='w', suffix='.txt') as f: + f.write(val) + infile = f.name + return infile + + def prepOut(workdir, name, val): + return op.join(workdir, '{}.txt'.format(name)) + + def load(path): + try: + with open(path, "r") as f: + return f.read() + except Exception: return None + + def decorator(func): + fot = _FileOrThing(func, + prepIn, + prepOut, + load, + fslpath.removeExt, + *args, + **kwargs) + + def wrapper(*args, **kwargs): + return fot(*args, **kwargs) + + return _update_wrapper(wrapper, func) + + return decorator -- GitLab