
import os
import time
import signal
import logging
import subprocess


""" Binary utilities """

def run(args, stdin=None):
    """Executes a command and waits for the result.

    Parameters
    ----------
    args : list
        The list of arguments for the program to execute. Arguments should be
        formatted as for the ``subprocess.Popen`` constructor.
    stdin : str or bytes
        String or bytes containing the input stream for the process.

    Returns
    -------
    CompletedProcess
        An instance of CompletedProcess containing the information about
        the executed process, including stdout, stderr and running time.

    Raises
    ------
    CalledProcessError
        When the process returns an error.
    """
    log = logging.getLogger(__name__)
    log.debug('Executing command with args: {}', args)
    start = time.time()
    sigint = signal.getsignal(signal.SIGINT)
    signal.signal(signal.SIGINT, lambda *args: None)
    with subprocess.Popen(args, bufsize=1, universal_newlines=True,
                          stdin=subprocess.PIPE,
                          stdout=subprocess.PIPE,
                          stderr=subprocess.PIPE) as process:
        try:
            out, err = process.communicate(stdin)
        except (KeyboardInterrupt, SystemExit):
            process.kill()
            os.killpg(os.getpgid(process.pid), signal.SIGTERM)
            out, err = process.communicate(stdin)
        finally:
            ret = process.poll()
            signal.signal(signal.SIGINT, sigint)
    elapsed = time.time() - start
    log.debug('Done. Running time: {0:.2f} seconds'.format(elapsed))
    process = subprocess.CompletedProcess(args, ret, out, err)
    #process.check_returncode()
    return process


@@ -1240,32 +1240,65 @@
 municate(stdin)%0A
+            ret = process.poll()%0A
         except (
@@ -1296,17 +1296,16 @@
  except 
-(
 Keyboard
@@ -1317,21 +1317,8 @@
 rupt
-, SystemExit)
 :%0A  
@@ -1467,49 +1467,36 @@
     
-finally:%0A            ret = process.poll()
+    ret = 0%0A        finally:
 %0A   
@@ -1715,9 +1715,8 @@
     
-#
 proc

set ret=0 when keyboard interrupt and restore checkreturncode