Given a pcap filename, get the commandline to run.

        :param pcap: Pcap filename to scan
        :param logs: Output directory for logs
        :returns: list of command args to scan supplied pcap file
189680
def _suri_cmd(self, pcap, logs):
        
        cmdline = "'{0}' -c '{1}' -l '{2}' {3} -r '{4}'" \
            .format(self.conf['path'], self.conf['config'],
                    logs, self.conf['extra_args'] or '', pcap)
        # can't seem to capture stderr on windows
        # unless launched via cmd shell
        if 'nt' in os.name:
            cmdline = "cmd.exe /c " + cmdline
        return shlex.split(cmdline)
545925
def create_argument_parser():
    
    parser = argparse.ArgumentParser(prog='lograptor', description=__description__, add_help=False)
    parser.usage = """%(prog)s [options] PATTERN [FILE ...]
    %(prog)s [options] [-e PATTERN | -f FILE] [FILE ...]
    Try '%(prog)s --help' for more information."""

    group = parser.add_argument_group("General Options")
    group.add_argument(
        "--conf", dest="cfgfiles", action='append', default=None, metavar="FILE",
        help="use a specific configuration file"
    )
    group.add_argument(
        "-d", dest="loglevel", default=2, type=int, metavar="[0-4]", choices=range(5),
        help="Logging level (default is 2, use 4 for debug). A level of 0 suppress also "
             "error messages about nonexistent or unreadable files."
    )
    group.add_argument('-V', '--version', action='version', version=__version__)
    group.add_argument('--help', action='help', help="show this help message and exit")

    group = parser.add_argument_group("Scope Selection")
    group.add_argument(
        "-a", "--apps", metavar='APP[,APP...]', type=comma_separated_string,
        default=[], help="process the log lines related to a list of applications"
    )
    group.add_argument(
        "--hosts", metavar="HOSTNAME/IP[,HOSTNAME/IP...]", type=comma_separated_string,
        default=[], help="process the log lines related to an hostname/IP"
    )
    group.add_argument(
        "-F", "--filter", metavar="FIELD=PATTERN[,FIELD=PATTERN...]",
        action="append", dest="filters", type=filter_spec, default=[],
        help="process the log lines that match all the conditions for rule's field values"
    )
    group.add_argument(
        "--time", metavar="HH:MM,HH:MM", type=TimeRange, action="store", dest="time_range",
        help="process the log lines related to a time range"
    )
    group.add_argument(
        "--date", metavar="[YYYY]MMDD[,[YYYY]MMDD]", action="store", dest="time_period",
        type=date_interval_spec, help="restrict the search scope to a date or a date interval"
    )
    group.add_argument(
        "--last", action="store", dest="time_period", type=last_period_spec,
        metavar="[hour|day|week|month|Nh|Nd|Nw|Nm]",
        help="restrict the search scope to a previous time period"
    )

    group = parser.add_argument_group("Matcher Selection")
    group.add_argument(
        "-G", "--ruled", dest='matcher', action=StoreOptionAction,
        help="use patterns and application rules (default)"
    )
    group.add_argument(
        "-X", "--unruled", dest='matcher', action=StoreOptionAction,
        help="use patterns only, skip application rules"
    )
    group.add_argument(
        "-U", "--unparsed", dest='matcher', action=StoreOptionAction,
        help="match the patterns, don't match any application rule"
    )

    group = parser.add_argument_group("Matching Control")
    group.add_argument(
        "-e", "--regexp", metavar="PATTERN", dest="patterns", default=[],
        action="append", help="use PATTERN for matching"
    )
    group.add_argument(
        "-f", "--file", metavar="FILE", dest="pattern_files", default=[],
        action="append", help="obtain patterns from FILE"
    )
    group.add_argument(
        "-i", "--ignore-case", action="store_true", dest="case", default=False,
        help="ignore case distinctions"
    )
    group.add_argument(
        "-v", "--invert-match", action="store_true", dest="invert", default=False,
        help="invert the sense of patterns regexp matching"
    )
    group.add_argument(
        "-w", "--word-regexp", action="store_true", dest="word", default=False,
        help="force PATTERN to match only whole words"
    )

    group = parser.add_argument_group("General Output Control")
    group.add_argument(
        "--output", default=['stdout'], metavar='CHANNEL[,CHANNEL...]', dest='channels',
        type=comma_separated_string, help="send output to channels (default: ['stdout'])"
    )
    group.add_argument(
        "-c", "--count", action="store_true", default=False,
        help="print only a count of matching lines per FILE"
    )
    group.add_argument(
        "--color", default='auto', nargs='?', choices=['auto', 'always', 'never'],
        help="use markers to highlight the matching strings"
    )
    group.add_argument(
        "-L", "--files-without-match", action="store_false", dest="files_with_match", default=None,
        help="print only names of FILEs containing no match"
    )
    group.add_argument(
        "-l", "--files-with-match", action="store_true", dest="files_with_match",
        help="print only names of FILEs containing matches"
    )
    group.add_argument(
        "-m", "--max-count", metavar='NUM', action="store", type=positive_integer, default=0,
        help="stop after NUM matches"
    )
    group.add_argument(
        "-o", "--only-matching", action="store_true", default=False,
        help="show only the part of a line matching PATTERN"
    )
    group.add_argument(
        "-q", "--quiet", action="store_true", default=False, help="suppress all normal output"
    )
    group.add_argument(
        "-s", "--no-messages", action="store_const", const=0, dest='loglevel',
        help="suppress error messages (equivalent to -d 0)"
    )

    group = parser.add_argument_group("Output Data Control")
    group.add_argument(
        "--report", metavar='NAME', nargs='?', default=False,
        help="produce a report at the end of processing"
    )
    group.add_argument(
        "--ip-lookup", action="store_true", default=False,
        help="translate IP addresses to DNS names"
    )
    group.add_argument(
        "--uid-lookup", action="store_true", default=False,
        help="translate UIDs to usernames"
    )
    group.add_argument(
        "--anonymize", action="store_true", default=False,
        help="anonymize defined rule's fields value"
    )

    group = parser.add_argument_group("Output Line Prefix Control")
    group.add_argument(
        "-n", "--line-number", action="store_true", default=False,
        help="print line number with output lines"
    )
    group.add_argument(
        "-H", "--with-filename", action="store_true", dest="with_filename", default=None,
        help="print the file name for each match"
    )
    group.add_argument(
        "-h", "--no-filename", action="store_false", dest="with_filename", default=None,
        help="suppress the file name prefix on output"
    )

    group = parser.add_argument_group("Context Line Control")
    group.add_argument(
        "-T", "--thread", action="store_true", default=False,
        help="the context is the log thread of the application"
    )
    group.add_argument(
        "-B", "--before-context", metavar='NUM', type=positive_integer, default=0,
        help="print NUM lines of leading context"
    )
    group.add_argument(
        "-A", "--after-context", metavar='NUM', type=positive_integer, default=0,
        help="print NUM lines of trailing context"
    )
    group.add_argument(
        "-C", "--context", metavar='NUM', type=positive_integer, default=0,
        help="print NUM lines of output context"
    )
    group.add_argument(
        "--group-separator", metavar='SEP', default='--',
        help="use SEP as a group separator. By default SEP is double hyphen (--)."
    )
    group.add_argument(
        "--no-group-separator", dest="group_separator", action="store_const", const='',
        help="use empty string as a group separator"
    )

    group = parser.add_argument_group("File and Directory Selection")
    group.add_argument(
        "-r", "--recursive", action="store_true", default=False,
        help="read all files under each directory, recursively"
    )
    group.add_argument(
        "-R", "--dereference-recursive", action="store_true", default=False,
        help="likewise, but follow all symlinks"
    )
    group.add_argument(
        "--include", metavar='GLOB', default=[], action="append",
        help="search only files that match GLOB"
    )
    group.add_argument(
        "--exclude", metavar='GLOB', default=[], action="append",
        help="skip files and directories matching GLOB"
    )
    group.add_argument(
        "--exclude-from", metavar='FILE', default=[], action="append",
        help="skip files matching any file pattern from FILE"
    )
    group.add_argument(
        "--exclude-dir", metavar='DIR', default=[], action="append",
        help="exclude directories matching the pattern DIR"
    )

    parser.add_argument(
        'files', metavar='[FILE ...]', nargs='*',
        help='Input files. Each argument can be a file path or a glob pathname. '
             'A "-" stands for standard input. If no arguments are given then processes '
             'all the files included within the scope of the selected applications.'
    )
    return parser
813634
def run_cmsearch(fastas, threads, cm):
    
    out = []
    for fasta in fastas:
        cmsearch = '%s.23S.cmsearch' % (fasta.name.rsplit('.', 1)[0])
        if os.path.exists(cmsearch) is False:
            p = Popen('\
                    cmsearch --cpu %s --hmmonly --acc --noali -T -1 --tblout %s %s %s >> cmsearch.log' \
                    % (threads, cmsearch, cm, fasta.name), shell = True)
            p.communicate()
        else:
            print('# cmsearch output found: %s' % (cmsearch), file=sys.stderr)
        out.append(open(cmsearch))
    return out
1141479
def get_logger(name, file_name=None, stream=None, template=None, propagate=False, level=None):
    

    logger = logging.getLogger(name)
    running_tests = (
        'test' in sys.argv  # running with setup.py
        or sys.argv[0].endswith('py.test'))  # running with py.test
    if running_tests and not level:
        # testing without level, this means tester does not want to see any log messages.
        level = logging.CRITICAL

    if not level:
        level = logging.INFO
    logger.setLevel(level)
    logger.propagate = propagate

    formatter = logging.Formatter(template)

    if not stream:
        stream = sys.stdout

    logger.handlers = []
    handler = logging.StreamHandler(stream=stream)
    handler.setFormatter(formatter)
    logger.addHandler(handler)

    if file_name:
        handler = logging.FileHandler(file_name)
        handler.setFormatter(logging.Formatter('%(asctime)s '+template))
        logger.addHandler(handler)

    return logger
323806
def Logs(loggername, echo=True, debug=False, chatty=False, loglevel=logging.INFO, logfile=None, logpath=None, fileHandler=None):
    
    log = logging.getLogger(loggername)

    if fileHandler is None:
        if logfile is None:
            logFilename = _ourName
        else:
            logFilename = logfile

        if '.log' not in logFilename:
            logFilename = '%s.log' % logFilename

        if logpath is not None:
            logFilename = os.path.join(logpath, logFilename)

        _handler   = logging.FileHandler(logFilename)
        _formatter = logging.Formatter('%(asctime)s %(levelname)-7s %(message)s')

        _handler.setFormatter(_formatter)
        log.addHandler(_handler)
        # logging.fileHandler = _handler
    else:
        log.addHandler(fileHandler)
        # logging.fileHandler = fileHandler

    if echo:
        echoHandler = logging.StreamHandler()
        if chatty:
            echoFormatter = logging.Formatter('%(asctime)s %(levelname)-7s %(processName)s[%(process)d]: %(message)s')
        else:
            echoFormatter = logging.Formatter('%(asctime)s %(levelname)-7s %(message)s')
        echoHandler.setFormatter(echoFormatter)
        log.addHandler(echoHandler)

    if debug:
        log.setLevel(logging.DEBUG)
    else:
        log.setLevel(loglevel)

    atexit.register(shutdownLogging)
640458
def execute(self, input_data):
        '''  '''

        # Grab the Bro log handles from the input
        bro_logs = input_data['pcap_bro']

        # Weird log
        if 'weird_log' in bro_logs:
            stream = self.workbench.stream_sample(bro_logs['weird_log'])
            self.weird_log_graph(stream)

        # HTTP log
        gsleep()
        stream = self.workbench.stream_sample(bro_logs['http_log'])
        self.http_log_graph(stream)

        # Files log
        gsleep()
        stream = self.workbench.stream_sample(bro_logs['files_log'])
        self.files_log_graph(stream)

        return {'output':'go to http://localhost:7474/browser and execute this query "match (s:origin), (t:file), p=allShortestPaths((s)--(t)) return p"'}
247281
def parse_command_line(args):
    
    parser = argparse.ArgumentParser(
        description=(
            "Holocron is an easy and lightweight static blog generator, "
            "based on markup text and Jinja2 templates."),
        epilog=(
            "With no CONF, read .holocron.yml in the current working dir. "
            "If no CONF found, the default settings will be used."))

    parser.add_argument(
        "-c", "--conf", dest="conf", default=".holocron.yml",
        help="set path to the settings file")

    parser.add_argument(
        "-q", "--quiet", dest="verbosity", action="store_const",
        const=logging.CRITICAL, help="show only critical errors")

    parser.add_argument(
        "-v", "--verbose", dest="verbosity", action="store_const",
        const=logging.INFO, help="show additional messages")

    parser.add_argument(
        "-d", "--debug", dest="verbosity", action="store_const",
        const=logging.DEBUG, help="show all messages")

    parser.add_argument(
        "--version", action="version",
        version=pkg_resources.get_distribution("holocron").version,
        help="show the holocron version and exit")

    command_parser = parser.add_subparsers(
        dest="command", help="command to execute")

    run_parser = command_parser.add_parser("run")
    run_parser.add_argument("pipe", help="a pipe to run")

    # parse cli and form arguments object
    arguments = parser.parse_args(args)

    # if no commands are specified display help
    if arguments.command is None:
        parser.print_help()
        parser.exit(1)

    return arguments
388041
def get_access_logs(config):
    
    access_log = Literal("access_log") + ZeroOrMore(parameter) + semicolon
    access_log.ignore(pythonStyleComment)

    for directive in access_log.searchString(config).asList():
        path = directive[1]
        if path == 'off' or path.startswith('syslog:'):
            # nothing to process here
            continue

        format_name = 'combined'
        if len(directive) > 2 and '=' not in directive[2]:
            format_name = directive[2]

        yield path, format_name
713688
def ParseArguments(self):
    
    loggers.ConfigureLogging()

    argument_parser = argparse.ArgumentParser(
        description=self.DESCRIPTION, epilog=self.EPILOG, add_help=False,
        formatter_class=argparse.RawDescriptionHelpFormatter)

    self.AddBasicOptions(argument_parser)

    helpers_manager.ArgumentHelperManager.AddCommandLineArguments(
        argument_parser, names=['storage_file'])

    data_location_group = argument_parser.add_argument_group(
        'data location arguments')

    argument_helper_names = ['artifact_definitions', 'data_location']
    helpers_manager.ArgumentHelperManager.AddCommandLineArguments(
        data_location_group, names=argument_helper_names)

    extraction_group = argument_parser.add_argument_group(
        'extraction arguments')

    argument_helper_names = [
        'artifact_filters', 'extraction', 'filter_file', 'hashers',
        'parsers', 'yara_rules']
    helpers_manager.ArgumentHelperManager.AddCommandLineArguments(
        extraction_group, names=argument_helper_names)

    self.AddStorageMediaImageOptions(extraction_group)
    self.AddTimeZoneOption(extraction_group)
    self.AddVSSProcessingOptions(extraction_group)
    self.AddCredentialOptions(extraction_group)

    info_group = argument_parser.add_argument_group('informational arguments')

    self.AddInformationalOptions(info_group)

    info_group.add_argument(
        '--info', dest='show_info', action='store_true', default=False,
        help='Print out information about supported plugins and parsers.')

    info_group.add_argument(
        '--use_markdown', '--use-markdown', dest='use_markdown',
        action='store_true', default=False, help=(
            'Output lists in Markdown format use in combination with '
            '"--hashers list", "--parsers list" or "--timezone list"'))

    info_group.add_argument(
        '--no_dependencies_check', '--no-dependencies-check',
        dest='dependencies_check', action='store_false', default=True,
        help='Disable the dependencies check.')

    self.AddLogFileOptions(info_group)

    helpers_manager.ArgumentHelperManager.AddCommandLineArguments(
        info_group, names=['status_view'])

    output_group = argument_parser.add_argument_group('output arguments')

    helpers_manager.ArgumentHelperManager.AddCommandLineArguments(
        output_group, names=['text_prepend'])

    processing_group = argument_parser.add_argument_group(
        'processing arguments')

    self.AddPerformanceOptions(processing_group)
    self.AddProcessingOptions(processing_group)

    processing_group.add_argument(
        '--sigsegv_handler', '--sigsegv-handler', dest='sigsegv_handler',
        action='store_true', default=False, help=(
            'Enables the SIGSEGV handler. WARNING this functionality is '
            'experimental and will a deadlock worker process if a real '
            'segfault is caught, but not signal SIGSEGV. This functionality '
            'is therefore primarily intended for debugging purposes'))

    profiling_group = argument_parser.add_argument_group('profiling arguments')

    helpers_manager.ArgumentHelperManager.AddCommandLineArguments(
        profiling_group, names=['profiling'])

    storage_group = argument_parser.add_argument_group('storage arguments')

    helpers_manager.ArgumentHelperManager.AddCommandLineArguments(
        storage_group, names=['storage_format'])

    argument_parser.add_argument(
        self._SOURCE_OPTION, action='store', metavar='SOURCE', nargs='?',
        default=None, type=str, help=(
            'Path to a source device, file or directory. If the source is '
            'a supported storage media device or image file, archive file '
            'or a directory, the files within are processed recursively.'))

    try:
      options = argument_parser.parse_args()
    except UnicodeEncodeError:
      # If we get here we are attempting to print help in a non-Unicode
      # terminal.
      self._output_writer.Write('\n')
      self._output_writer.Write(argument_parser.format_help())
      return False

    # Properly prepare the attributes according to local encoding.
    if self.preferred_encoding == 'ascii':
      logger.warning(
          'The preferred encoding of your system is ASCII, which is not '
          'optimal for the typically non-ASCII characters that need to be '
          'parsed and processed. The tool will most likely crash and die, '
          'perhaps in a way that may not be recoverable. A five second delay '
          'is introduced to give you time to cancel the runtime and '
          'reconfigure your preferred encoding, otherwise continue at own '
          'risk.')
      time.sleep(5)

    if self._process_archives:
      logger.warning(
          'Scanning archive files currently can cause deadlock. Continue at '
          'your own risk.')
      time.sleep(5)

    try:
      self.ParseOptions(options)
    except errors.BadConfigOption as exception:
      self._output_writer.Write('ERROR: {0!s}\n'.format(exception))
      self._output_writer.Write('\n')
      self._output_writer.Write(argument_parser.format_usage())
      return False

    self._command_line_arguments = self.GetCommandLineArguments()

    loggers.ConfigureLogging(
        debug_output=self._debug_mode, filename=self._log_file,
        quiet_mode=self._quiet_mode)

    return True
522155
def parse_files(self):
        
        log_re = self.log_format_regex
        log_lines = []
        for log_file in self.matching_files():
            with open(log_file) as f:
                matches = re.finditer(log_re, f.read())
                for match in matches:
                    log_lines.append(match.groupdict())
        return log_lines
22816
def _main_cli(self):
        
        self.logger.info("SMAC call: %s" % (" ".join(sys.argv)))

        cmd_reader = CMDReader()
        args, _ = cmd_reader.read_cmd()

        root_logger = logging.getLogger()
        root_logger.setLevel(args.verbose_level)
        logger_handler = logging.StreamHandler(
                stream=sys.stdout)
        if root_logger.level >= logging.INFO:
            formatter = logging.Formatter(
                "%(levelname)s:\t%(message)s")
        else:
            formatter = logging.Formatter(
                "%(asctime)s:%(levelname)s:%(name)s:%(message)s",
                "%Y-%m-%d %H:%M:%S")
        logger_handler.setFormatter(formatter)
        root_logger.addHandler(logger_handler)
        # remove default handler
        root_logger.removeHandler(root_logger.handlers[0])

        # Create defaults
        rh = None
        initial_configs = None
        stats = None
        incumbent = None

        # Create scenario-object
        scen = Scenario(args.scenario_file, [])

        if args.mode == "SMAC":
            optimizer = SMAC(
                scenario=scen,
                rng=np.random.RandomState(args.seed),
                runhistory=rh,
                initial_configurations=initial_configs,
                stats=stats,
                restore_incumbent=incumbent,
                run_id=args.seed)
        elif args.mode == "ROAR":
            optimizer = ROAR(
                scenario=scen,
                rng=np.random.RandomState(args.seed),
                runhistory=rh,
                initial_configurations=initial_configs,
                run_id=args.seed)
        elif args.mode == "EPILS":
            optimizer = EPILS(
                scenario=scen,
                rng=np.random.RandomState(args.seed),
                runhistory=rh,
                initial_configurations=initial_configs,
                run_id=args.seed)
        else:
            optimizer = None

        return optimizer
1177522
def do_processlist(self, arg):
        
        if self.cmdprefix:
            raise CmdError("prefix not allowed")
        if arg:
            raise CmdError("too many arguments")
        system   = self.debug.system
        pid_list = self.debug.get_debugee_pids()
        if pid_list:
            print("Process ID   File name")
            for pid in pid_list:
                if   pid == 0:
                    filename = "System Idle Process"
                elif pid == 4:
                    filename = "System"
                else:
                    filename = system.get_process(pid).get_filename()
                    filename = PathOperations.pathname_to_filename(filename)
                print("%-12d %s" % (pid, filename))
328955
def run():
    

    global WORKBENCH
    
    # Grab grab_server_argsrver args
    args = client_helper.grab_server_args()

    # Start up workbench connection
    WORKBENCH = zerorpc.Client(timeout=300, heartbeat=60)
    WORKBENCH.connect('tcp://'+args['server']+':'+args['port'])

    data_path = os.path.join(
        os.path.dirname(os.path.realpath(__file__)), '../data/pcap')
    file_list = [os.path.join(data_path, child) for child in \
                os.listdir(data_path)]
    results = []
    for filename in file_list:

        # Skip OS generated files
        if '.DS_Store' in filename: continue

        # Process the pcap file
        with open(filename,'rb') as f:
            md5 = WORKBENCH.store_sample(f.read(), filename, 'pcap')
            result = WORKBENCH.work_request('view_pcap', md5)
            result.update(WORKBENCH.work_request('meta', result['view_pcap']['md5']))
            result['filename'] = result['meta']['filename'].split('/')[-1]
            results.append(result)

    return results
1197287
def get_log_dir(self, conf_file):
        
        log_dir = None

        with open(conf_file, 'r') as conf_f:
            for line in conf_f:
                line = line.split('#')[0].strip()

                try:
                    (key, value) = line.split('=', 1)
                    if key.strip() == 'log-dir':
                        log_dir = value.strip()
                except ValueError:
                    pass

        return log_dir
340055
def main(argv=None):
    

    import logging

    if argv is None:
        argv = sys.argv

    prs = get_option_parser()
    (opts, args) = prs.parse_args(args=argv)

    if not opts.quiet:
        _format = None
        _format = "%(levelname)s\t%(message)s"
        # _format = "%(message)s"
        logging.basicConfig(format=_format)

    log = logging.getLogger('repos')

    if opts.verbose:
        log.setLevel(logging.DEBUG)
    elif opts.quiet:
        log.setLevel(logging.ERROR)
    else:
        log.setLevel(logging.INFO)
    if not opts.scan:
        opts.scan = ['.']

    if opts.scan:
        # if not opts.reports:
        #     opts.reports = ['pip']
        if opts.reports or opts.thg_report:
            opts.reports = [s.strip().lower() for s in opts.reports]
            if 'thg' in opts.reports:
                opts.thg_report = True
                opts.reports.remove('thg')
            # repos = []
            # for _path in opts.scan:
            #     repos.extend(find_unique_repos(_path))
            log.debug("SCANNING PATHS: %s" % opts.scan)
            repos = chain(*imap(find_unique_repos, opts.scan))

            if opts.reports and opts.thg_report:
                repos = list(repos)
                # TODO: tee

            if opts.reports:
                for report in opts.reports:
                    list(do_repo_report(repos, report=report))
            if opts.thg_report:
                do_tortoisehg_report(repos, output=sys.stdout)

        else:
            opts.scan = '.'
            list(do_repo_report(
                find_unique_repos(opts.scan),
                report='sh'))
    return 0
989637
def execute_log(args, root_dir):
    
    # Print the logs of all specified processes
    if args.get('keys'):
        config_dir = os.path.join(root_dir, '.config/pueue')
        queue_path = os.path.join(config_dir, 'queue')
        if os.path.exists(queue_path):
            queue_file = open(queue_path, 'rb')
            try:
                queue = pickle.load(queue_file)
            except Exception:
                print('Queue log file seems to be corrupted. Aborting.')
                return
            queue_file.close()
        else:
            print('There is no queue log file. Aborting.')
            return

        for key in args.get('keys'):
            # Check if there is an entry with this key
            if queue.get(key) and queue[key]['status'] in ['failed', 'done']:
                entry = queue[key]
                print('Log of entry: {}'.format(key))
                print('Returncode: {}'.format(entry['returncode']))
                print('Command: {}'.format(entry['command']))
                print('Path: {}'.format(entry['path']))
                print('Start: {}, End: {} \n'.format(entry['start'], entry['end']))

                # Write STDERR
                if len(entry['stderr']) > 0:
                    print(Color('{autored}Stderr output: {/autored}\n    ') + entry['stderr'])

                # Write STDOUT
                if len(entry['stdout']) > 0:
                    print(Color('{autogreen}Stdout output: {/autogreen}\n    ') + entry['stdout'])
            else:
                print('No finished process with key {}.'.format(key))

    # Print the log of all processes
    else:
        log_path = os.path.join(root_dir, '.local/share/pueue/queue.log')
        log_file = open(log_path, 'r')
        print(log_file.read())
542140
def get_command_line_args():
    """"""
    parser = argparse.ArgumentParser(description='Send logs to Django Sentry.')

    parser.add_argument('--sentryconfig', '-c', default=None,
                        help='A configuration file (.ini, .yaml) of some '
                             'Sentry integration to extract the Sentry DSN from')
    parser.add_argument('--sentrydsn', '-s', default="",
                        help='The Sentry DSN string (overrides -c)')
    parser.add_argument('--daemonize', '-d', default=False,
                        action='store_const', const=True,
                        help='Run this script in background')
    parser.add_argument('--follow', '-f', default="all",
                        help='Which logs to follow, default ALL')
    parser.add_argument('--nginxerrorpath', '-n', default=None,
                        help='Nginx error log path')

    return parser.parse_args()