Write to log file and exit if exit_status is present.
167341
def log(program, message, exit_status = nil, files = nil)
      File.open(File.join(@log_directory, @log_file), "a") do |log|
        log.puts ""
        log.puts Time.now.to_s + " " + program
        log.puts message
        log.puts ""
      end

      if exit_status
        remove_files(files) unless files.nil?
        exit exit_status.to_i
      end
    end
463640
def write (self, s, **args):
        
        if self.filename is not None:
            self.start_fileoutput()
        if self.fd is None:
            # Happens when aborting threads times out
            log.warn(LOG_CHECK, "writing to unitialized or closed file")
        else:
            try:
                self.fd.write(s, **args)
            except IOError:
                msg = sys.exc_info()[1]
                log.warn(LOG_CHECK,
                    "Could not write to output file: %s\n"
                    "Disabling log output of %s", msg, self)
                self.close_fileoutput()
                self.fd = dummy.Dummy()
                self.is_active = False
879186
def check_call_no_output(args):
    
    logger = logging.getLogger(__name__)
    logger.debug("running %s", args)
    process = subprocess.Popen(
        args,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
    )
    (res_stdout, res_stderr) = process.communicate()
    if process.returncode:
        res_stdout = res_stdout
        res_stderr = res_stderr
        print(res_stdout, end='')
        print(res_stderr, end='')
        raise ValueError('exit code from [{}] was [{}]'.format(" ".join(args), process.returncode))
428713
def log_status(cmd, message, verbose, color = false)
      return unless verbose

      cmd = cmd.to_s.rjust(12)
      if color
        i = cmd.index(/[a-z]/)
        cmd = cmd[0...i] + decorate(cmd[i..-1], color)
      end

      message = "#{cmd}  #{message}"
      message += "\n" unless message.end_with?("\n")

      @output.print(message)
      @output.flush
    end
243535
def exit_with_mapped_status(http_status):
    
    # get the mapping by looking up the state and getting the mapping attr
    mapping = click.get_current_context().ensure_object(CommandState).http_status_map

    # if there is a mapped exit code, exit with that. Otherwise, exit 1
    if http_status in mapping:
        sys.exit(mapping[http_status])
    else:
        sys.exit(1)
1104114
def exit_on_error(self):
        """"""
        if self.exit_code:
            if self.errmsg is not None:
                logger.show("Exiting due to " + self.errmsg + ".")
                self.errmsg = None
            if self.using_jobs:
                kill_children()
            sys.exit(self.exit_code)
1114942
def end_log_output(self, **kwargs):
        """"""
        kwargs.update(dict(
            downloaded_bytes=self.downloaded_bytes,
            num_urls = len(self.result_cache),
        ))
        self.logger.end_log_output(**kwargs)
544610
def _at_exit(self):
        

        if self.process_exit:

            try:

                term = self.term

                if self.set_scroll:
                    term.reset()
                else:
                    term.move_to(0, term.height)

                self.term.feed()

            except ValueError:  # Possibly closed file handles
                pass
1271054
def exit_ok(self, message, exit_code=None):
        
        logger.info("Exiting...")
        if message:
            logger.info("-----")
            logger.error("Exit message: %s", message)
            logger.info("-----")

        self.request_stop()

        if exit_code is not None:
            exit(exit_code)
345069
def _exit_handler(self):
        

        # TODO: consider handling sys.stderr/sys.stdout exceptions related to
        # TODO (cont.): order of interpreter vs. subprocess shutdown signal receipt.
        # TODO (cont.): see https://bugs.python.org/issue11380


        # Make the cleanup file executable if it exists
        if os.path.isfile(self.cleanup_file):
            # Make the cleanup file self destruct.
            with open(self.cleanup_file, "a") as myfile:
                myfile.write("rm " + self.cleanup_file + "\n")
            os.chmod(self.cleanup_file, 0o755)

        # If the pipeline hasn't completed successfully, or already been marked
        # as failed, then mark it as failed now.

        if not self._has_exit_status:
            print("Pipeline status: {}".format(self.status))
            self.fail_pipeline(Exception("Pipeline failure. See details above."))

        if self.tee:
            self.tee.kill()
1165155
def write_eof(self):
        """"""
        self._check_status()
        if not self._writable:
            raise TransportError('transport is not writable')
        if self._closing:
            raise TransportError('transport is closing')
        try:
            self._handle.shutdown(self._on_write_complete)
        except pyuv.error.UVError as e:
            self._error = TransportError.from_errno(e.args[0])
            self.abort()
            raise compat.saved_exc(self._error)
        self._write_buffer_size += 1
1332450
def write(self, log, rotate=False):
        """"""
        # Get path for logfile
        if rotate:
            timestamp = time.strftime('-%Y%m%d-%H%M')
            logPath = os.path.join(self.log_dir, 'queue{}.log'.format(timestamp))
        else:
            logPath = os.path.join(self.log_dir, 'queue.log')

        # Remove existing Log
        if os.path.exists(logPath):
            os.remove(logPath)

        log_file = open(logPath, 'w')
        log_file.write('Pueue log for executed Commands: \n \n')

        # Format, color and write log
        for key, logentry in log.items():
            if logentry.get('returncode') is not None:
                try:
                    # Get returncode color:
                    returncode = logentry['returncode']
                    if returncode == 0:
                        returncode = Color('{autogreen}' + '{}'.format(returncode) + '{/autogreen}')
                    else:
                        returncode = Color('{autored}' + '{}'.format(returncode) + '{/autored}')

                    # Write command id with returncode and actual command
                    log_file.write(
                        Color('{autoyellow}' + 'Command #{} '.format(key) + '{/autoyellow}') +
                        'exited with returncode {}: \n'.format(returncode) +
                        '"{}" \n'.format(logentry['command'])
                    )
                    # Write path
                    log_file.write('Path: {} \n'.format(logentry['path']))
                    # Write times
                    log_file.write('Start: {}, End: {} \n'
                                   .format(logentry['start'], logentry['end']))

                    # Write STDERR
                    if logentry['stderr']:
                        log_file.write(Color('{autored}Stderr output: {/autored}\n    ') + logentry['stderr'])

                    # Write STDOUT
                    if len(logentry['stdout']) > 0:
                        log_file.write(Color('{autogreen}Stdout output: {/autogreen}\n    ') + logentry['stdout'])

                    log_file.write('\n')
                except Exception as a:
                    print('Failed while writing to log file. Wrong file permissions?')
                    print('Exception: {}'.format(str(a)))

        log_file.close()
976349
def __exitfunction(self):
        '''
        
        '''
        if self._hook.exit_code is None and self._hook.exception is None:
            print("Check did not exit! You should call an exit code method.")
            sys.stdout.flush()
            os._exit(1)
        elif self._hook.exception:
            print("Check failed to run: %s, %s" %
                  (sys.last_type, traceback.format_tb(sys.last_traceback)))
            sys.stdout.flush()
            os._exit(2)
1219755
def write_to_logfile(logfile, out, err, cmd):
    
    with open(logfile, 'a+') as outfile:
        outfile.write('Command used: {}\n\n'.format(cmd))
        outfile.write('STDOUT: {}\n\n'.format(out))
        outfile.write('STDERR: {}\n\n'.format(err))
843280
def cleanup(self):
        """"""
        try:
            self.exit_config_mode()
        except Exception:
            # Always try to send 'exit' regardless of whether exit_config_mode works or not.
            pass
        self._session_log_fin = True
        self.write_channel("exit" + self.RETURN)
692241
private void blockFaultLogWriteStatus(SettableFuture<Boolean> written) {
        boolean logWritten = false;

        if (written != null) {
            try {
                logWritten = written.get();
            } catch (InterruptedException e) {
            } catch (ExecutionException e) {
                if (tmLog.isDebugEnabled()) {
                    tmLog.debug("Could not determine fault log state for partition: " + m_partitionId, e);
                }
            }
            if (!logWritten) {
                tmLog.warn("Attempted fault log not written for partition: " + m_partitionId);
            }
        }
    }
325094
def log(self, msg):
        '''
        '''
        if self.logfile:
            fd = self.logfile.fileno()
        else:
            fd = sys.stdout.fileno()

        os.write(fd, ('%.3f %s\n' % (time.time(), msg)).encode('UTF-8'))