Redirect stdout/stderr to a file, using posix dup2.
550847
def posix_redirect_output(filename=None, permanent=True):
    
    sys.stdout.flush()
    sys.stderr.flush()

    stdout_fd = sys.stdout.fileno()
    stderr_fd = sys.stderr.fileno()

    if not permanent:
        stdout_fd_copy = os.dup(stdout_fd)
        stderr_fd_copy = os.dup(stderr_fd)

    if filename is None:
        out_fd, filename = tempfile.mkstemp()
    else:
        out_fd = os.open(filename, os.O_WRONLY | os.O_CREAT | os.O_TRUNC)

    try:
        # Redirect stdout and stderr to file
        os.dup2(out_fd, stdout_fd)
        os.dup2(out_fd, stderr_fd)

        yield filename
    finally:
        sys.stdout.flush()
        sys.stderr.flush()
        os.close(out_fd)

        if not permanent:
            os.dup2(stdout_fd_copy, stdout_fd)
            os.dup2(stderr_fd_copy, stderr_fd)
            os.close(stdout_fd_copy)
            os.close(stderr_fd_copy)
73758
def daemonize_posix(self):
        
        logger.info('daemonize_posix')
        try:
            pid = os.fork()
            if pid > 0:
                logger.debug('forked first child, pid = %d' % (pid,))
                return pid
            logger.debug('in child after first fork, pid = %d' % (pid, ))
        except OSError as error:
            logger.exception('fork #1')
            sys.stderr.write("fork #1 failed: %d (%s)\n" % (error.errno, error.strerror))
            sys.exit(1)

        # decouple from parent environment
        os.chdir("/")
        os.setsid()
        os.umask(0)

        # do second fork
        try:
            pid = os.fork()
            if pid > 0:
                # exit from second parent
                logger.debug('forked second child, pid = %d, exiting' % (pid,))
                sys.exit(0)
        except OSError as error:
            logger.exception('fork #2')
            sys.stderr.write("fork #2 failed: %d (%s)\n" % (error.errno, error.strerror))
            sys.exit(1)

        # redirect standard file descriptors
        logger.info('daemonized, pid = %d' % (pid, ))
        sys.stdin.flush()
        sys.stdout.flush()
        sys.stderr.flush()

        os.dup2(self.stdin.fileno(), sys.stdin.fileno())
        os.dup2(self.stdout.fileno(), sys.stdout.fileno())
        os.dup2(self.stderr.fileno(), sys.stderr.fileno())

        # write pidfile
        atexit.register(self.delpid)
        pid = str(os.getpid())
        with open(self.pidfile, 'w+') as fd:
            fd.write("%s\n" % pid)
813052
def warning(*args):
    """"""
    if sys.stdin.isatty():
        print('WARNING:', *args, file=sys.stderr)
    else:
        notify_warning(*args)
287107
def stderr_avail(self):
        """"""
        data = self.interpreter.stderr_write.empty_queue()
        if data:
            self.write(data, error=True)
            self.flush(error=True)
42276
def postprocess(output_filename, options):

    ''''''

    assert options.postprocess_cmd

    base, _ = os.path.splitext(output_filename)
    post_filename = base + options.postprocess_ext

    cmd = options.postprocess_cmd
    cmd = cmd.replace('%i', output_filename)
    cmd = cmd.replace('%o', post_filename)
    cmd = cmd.replace('%e', options.postprocess_ext)

    subprocess_args = shlex.split(cmd)

    if os.path.exists(post_filename):
        os.unlink(post_filename)

    if not options.quiet:
        print('  running "{}"...'.format(cmd), end=' ')
        sys.stdout.flush()

    try:
        result = subprocess.call(subprocess_args)
        before = os.stat(output_filename).st_size
        after = os.stat(post_filename).st_size
    except OSError:
        result = -1

    if result == 0:

        if not options.quiet:
            print('{:.1f}% reduction'.format(
                100*(1.0-float(after)/before)))

        return post_filename

    else:

        sys.stderr.write('warning: postprocessing failed!\n')
        return None
461561
def print_err(*args, **kwargs):
    
    if kwargs.get('file', None) is None:
        kwargs['file'] = sys.stderr
    print(*args, **kwargs)
152901
def redirect_io_to(log_file)
      log_file ||= "/dev/null"
      reopen_io STDIN, "/dev/null"
      reopen_io STDOUT, log_file, "a"
      reopen_io STDERR, STDOUT
      STDERR.sync = STDOUT.sync = true
    end
697831
def _emit_error(cls, message):
        """"""
        sys.stderr.write('ERROR: {message}\n'.format(message=message))
        sys.stderr.flush()
57364
def _safe_exit(start, output):
    
    try:
        sys.stdout.write(output)
        sys.stdout.flush()
    except TypeError:  # python3
        sys.stdout.write(str(output, 'utf-8'))
        sys.stdout.flush()
    except IOError:
        pass

    seconds = time.time() - start
    print("\n\n%5.3f seconds" % (seconds), file=sys.stderr)
974231
def redirect_std():
    
    stdin = sys.stdin
    stdout = sys.stdout
    if not sys.stdin.isatty():
        sys.stdin = open_raw("/dev/tty", "r", 0)
    if not sys.stdout.isatty():
        sys.stdout = open_raw("/dev/tty", "w", 0)

    return stdin, stdout
148598
def copyFile(input, output, replace=None):
    """"""

    _found = findFile(output)
    if not _found or (_found and replace):
        shutil.copy2(input, output)
264459
def shell_out_ignore_exitcode(cmd, stderr=STDOUT, cwd=None):
    """"""
    try:
        return shell_out(cmd, stderr=stderr, cwd=cwd)
    except CalledProcessError as c:
        return _clean_output(c.output)
694883
def interrupt_stdin_thread():
    """"""
    dupped_stdin = os.dup(0)  # Backup the stdin fd
    assert not the_stdin_thread.interrupt_asked  # Sanity check
    the_stdin_thread.interrupt_asked = True  # Not user triggered
    os.lseek(tempfile_fd, 0, 0)  # Rewind in the temp file
    os.dup2(tempfile_fd, 0)  # This will make raw_input() return
    pid = get_stdin_pid()
    os.kill(pid, signal.SIGWINCH)  # Try harder to wake up raw_input()
    the_stdin_thread.out_of_raw_input.wait()  # Wait for this return
    the_stdin_thread.interrupt_asked = False  # Restore sanity
    os.dup2(dupped_stdin, 0)  # Restore stdin
    os.close(dupped_stdin)
622000
def redirectSTDOUTtoDebugFile():
    """"""
    import sys
    kwargs = {}
    if sys.version_info >= (3,):
        kwargs["encoding"] = "utf8"
    sys.stdout = open(
        os.path.join(
            getDebugDirectory(),
            "{0}.stdout".format(getDebugIdentifier()),
        ),
        "w",
        1, # Buffering by line
        **kwargs
    )
    sys.stderr = open(
        os.path.join(
            getDebugDirectory(),
            "{0}.stderr".format(getDebugIdentifier()),
        ),
        "w",
        1, # Buffering by line
        **kwargs
    )
458383
def launch(program, sock, stderr=True, cwd=None, env=None):
        
        if stderr is True:
            err = sock # redirect to socket
        elif stderr is False:
            err = open(os.devnull, 'wb') # hide
        elif stderr is None:
            err = None # redirect to console

        p = subprocess.Popen(program,
                shell=type(program) not in (list, tuple),
                stdin=sock, stdout=sock, stderr=err,
                cwd=cwd, env=env,
                close_fds=True)

        sock.close()
        return p
874590
def stderr_with_input(cmd, stdin):
    """"""
    handle, gpg_stderr = stderr_handle()
    LOGGER.debug("GPG command %s", ' '.join(cmd))
    try:
        gpg_proc = subprocess.Popen(cmd,  # nosec
                                    stdout=subprocess.PIPE,
                                    stdin=subprocess.PIPE,
                                    stderr=gpg_stderr)

        output, _err = gpg_proc.communicate(polite_bytes(stdin))

        if handle:
            handle.close()

        return output
    except subprocess.CalledProcessError as exception:
        return gpg_error(exception, 'GPG variable encryption error')
    except OSError as exception:
        raise CryptoritoError("File %s not found" % exception.filename)
85465
def write_error(*args, **kwargs):
    """"""
    if _logger:
        kwargs.pop("end", None)
        kwargs.pop("file", None)
        _logger.error(*args, **kwargs)
    else:
        print(*args, file=sys.stderr, **kwargs)