コード例 #1
0
def main():
    """Provide the entry point to the subreddit_stats command."""
    parser = arg_parser(usage='usage: %(prog)s [options] SUBREDDIT VIEW')
    parser.add_argument(
        'subreddit', type=str, help='The subreddit to be analyzed')
    parser.add_argument(
        'view',
        type=str,
        help='The number of latest days or one of the reddit view (%s)' %
        ','.join(TOP_VALUES))
    parser.add_argument(
        '--verbose',
        type=int,
        default=0,
        help='0 for disabled, 1 for info, more for debug')

    options = parser.parse_args()

    if options.verbose == 1:
        LOGGER.setLevel(logging.INFO)
    elif options.verbose > 1:
        LOGGER.setLevel(logging.DEBUG)
    else:
        LOGGER.setLevel(logging.NOTSET)
    LOGGER.addHandler(logging.StreamHandler())

    srs = SubredditStats(options.subreddit)
    files = srs.run(options.view)
    if files:
        print('Written files: %s' % ' '.join(files))
    return 0
コード例 #2
0
ファイル: summary.py プロジェクト: freeboson/superplot
def main():
    # Select chain and info file with a GUI.
    # datafile = open_file_gui(add_pattern="*.txt")
    # infofile = open_file_gui(add_pattern="*.txt")

    parser = arg_parser(description='Superplot summary tool', conflict_handler='resolve')

    parser.add_argument('--data_file',
                        '-d',
                        help='Chain file to summarise',
                        type=str,
                        required=True)
    parser.add_argument('--info_file',
                        '-i',
                        help='Info file to summarise',
                        type=str,
                        default=None,
                        required=False)

    args = vars(parser.parse_args())

    datafile = os.path.abspath(args['data_file'])

    infofile = args['info_file']
    if infofile:
        infofile = os.path.abspath(infofile)

    # Load and label data
    labels, data = data_loader.load(infofile, datafile)

    summary_table = _summary_table(labels, data, datafile=datafile, infofile=infofile)
    return summary_table
コード例 #3
0
def main():
    """Provide the entry point to the subreddit_stats command."""
    parser = arg_parser(usage="usage: %(prog)s [options] SUBREDDIT VIEW")
    parser.add_argument("subreddit",
                        type=str,
                        help="The subreddit to be analyzed")
    parser.add_argument(
        "view",
        type=str,
        help="The number of latest days or one of the reddit view (%s)" %
        ",".join(TOP_VALUES),
    )
    parser.add_argument("--verbose",
                        type=int,
                        default=0,
                        help="0 for disabled, 1 for info, more for debug")

    options = parser.parse_args()

    if options.verbose == 1:
        LOGGER.setLevel(logging.INFO)
    elif options.verbose > 1:
        LOGGER.setLevel(logging.DEBUG)
    else:
        LOGGER.setLevel(logging.NOTSET)
    LOGGER.addHandler(logging.StreamHandler())

    srs = SubredditStats(options.subreddit)
    file = srs.run(options.view)
    if file:
        print("File written : " + file)
    return 0
コード例 #4
0
def main():
    """Provide the entry point to the user_since command."""
    parser = arg_parser(usage='usage: %(prog)s [options] file.csv')
    parser.add_argument('filename', type=str, help='The file with the list of usernames')
    parser.add_argument(
        '--verbose', type=int, default=0, help='0 for disabled, 1 for info, more for debug')
    options = parser.parse_args()

    if options.verbose == 1:
        LOGGER.setLevel(logging.INFO)
    elif options.verbose > 1:
        LOGGER.setLevel(logging.DEBUG)
    else:
        LOGGER.setLevel(logging.NOTSET)
    LOGGER.addHandler(logging.StreamHandler())
    process(options.filename)
コード例 #5
0
def main():
    """Provide the entry point to the command."""
    parser = arg_parser(usage='usage: %(prog)s t3 COMMAND [filename]')
    parser.add_argument('t3',
                        type=str,
                        help='The id of the source thread (es: 5npcrc)')
    parser.add_argument('command',
                        type=str,
                        help='text (body to txt) or csv (all to csv)')
    parser.add_argument('filename',
                        type=str,
                        default=None,
                        nargs='?',
                        help='The filename for the output')
    parser.add_argument('--verbose',
                        type=int,
                        default=0,
                        help='0 for disabled, 1 for info, more for debug')

    options = parser.parse_args()

    if options.verbose == 1:
        logger.setLevel(logging.INFO)
    elif options.verbose > 1:
        logger.setLevel(logging.DEBUG)
    else:
        logger.setLevel(logging.NOTSET)
    logger.addHandler(logging.StreamHandler())

    comments = get_comments(options.t3)

    default_filename = 'output'
    if options.command == 'text':
        output = '\n'.join(extract_bodies(comments))
        default_filename = '%s.txt'
    elif options.command == 'csv':
        default_filename = '%s.csv'
        output = to_csv(comments)

    if not options.filename:
        options.filename = default_filename % options.t3

    with open(options.filename, 'w', encoding='utf8') as fileout:
        fileout.write(output)
    return 0
コード例 #6
0
ファイル: run.py プロジェクト: innisfree/watch_multinest
def __main__():
    """
    Monitor MultiNest scan via command line arguments.
    """

    # Make parser for command line arguments

    parser = arg_parser(description="Monitor MultiNest scan")

    parser.add_argument("root", help="Prefix of MultiNest output filenames (root)", type=str)
    parser.add_argument(
        "--tol", dest="tol", help="MultiNest evidence tolerance factor (tol)", type=float, default=0.1, required=False
    )
    parser.add_argument(
        "--maxiter",
        dest="maxiter",
        help="MultiNest maximum number of iterations (maxiter)",
        type=int,
        default=float("inf"),
        required=False,
    )
    parser.add_argument(
        "--watch",
        dest="watch_mode",
        help="Whether to watch rather than snapshot",
        action="store_true",
        default=False,
        required=False,
    )

    # Fetch arguments

    tol = parser.parse_args().tol
    assert tol > 0.0, "tol <= 0: %s" % tol
    maxiter = parser.parse_args().maxiter
    assert maxiter > 0, "maxiter <= 0: %s" % maxiter
    root = parser.parse_args().root
    watch_mode = parser.parse_args().watch_mode

    if watch_mode:
        watch(root, tol, maxiter)
    else:
        print_snapshot(root, tol, maxiter)
コード例 #7
0
def main():
    """Provide the entry point to the approved command."""
    parser = arg_parser(usage='usage: %(prog)s [options] SUBREDDIT')
    parser.add_argument('subreddit',
                        type=str,
                        help='The subreddit to be analyzed')
    parser.add_argument('--verbose',
                        type=int,
                        default=0,
                        help='0 for disabled, 1 for info, more for debug')
    options = parser.parse_args()

    if options.verbose == 1:
        LOGGER.setLevel(logging.INFO)
    elif options.verbose > 1:
        LOGGER.setLevel(logging.DEBUG)
    else:
        LOGGER.setLevel(logging.NOTSET)
    LOGGER.addHandler(logging.StreamHandler())
    process(options.subreddit)
コード例 #8
0
def main():
    """Provide the entry point to the subreddit_stats command."""
    parser = arg_parser(usage='usage: %(prog)s [options] SUBREDDIT ACTION')
    parser.add_argument('subreddit',
                        type=str,
                        help='The subreddit or multireddit to be analyzed')
    parser.add_argument('action',
                        type=str,
                        help='The action to be performed: mail or csv')
    parser.add_argument('--days',
                        type=int,
                        default=1,
                        help='The days to be extracted')
    parser.add_argument('--score',
                        type=int,
                        default=40,
                        help='The minumum number of score to be included')
    parser.add_argument('--verbose',
                        type=int,
                        default=0,
                        help='0 for disabled, 1 for info, more for debug')

    options = parser.parse_args()

    if options.verbose == 1:
        LOGGER.setLevel(logging.INFO)
    elif options.verbose > 1:
        LOGGER.setLevel(logging.DEBUG)
    else:
        LOGGER.setLevel(logging.NOTSET)
    LOGGER.addHandler(logging.StreamHandler())

    multireddit = options.subreddit.split('/m/')
    if len(multireddit) > 1:
        subreddit = None
    else:
        multireddit = None
        subreddit = options.subreddit

    srs = SubredditStats(subreddit, multireddit, options.days)
    srs.run(options.action, score_limit=options.score)
コード例 #9
0
def main():
    parser = arg_parser(description='Superplot home directory setup',
                        conflict_handler='resolve')

    parser.add_argument('--dir',
                        '-d',
                        help='Location of user home directory',
                        type=str,
                        required=True)

    args = vars(parser.parse_args())

    # Create target directory if it doesn't exist

    user_dir = os.path.abspath(args['dir'])
    try:
        if not os.path.isdir(user_dir):
            os.mkdir(user_dir)
    except OSError as e:
        warnings.warn("Could not create home directory: {}".format(e.strerror))
        sys.exit(1)

    # Drop text file with user home dir location in script directory
    script_dir = os.path.dirname(os.path.realpath(__file__))
    home_dir_file = os.path.join(script_dir, "user_home.txt")
    with open(home_dir_file, "wb") as f:
        f.write(user_dir)

    # Copy config.yml. Prompt user to overwrite if already present.
    config_path = os.path.join(user_dir, "config.yml")
    copy_config = True

    if os.path.exists(config_path):

        print "config.yml already present. Please note that versions of this file " \
              "distributed with previous versions of superplot may not work with " \
              "this release. If you wish to compare your customised config.yml with " \
              "the current defaults, an example is distributed with the source code " \
              "(superplot/config.yml)."

        copy_config = prompt("Replace existing file: {}".format(config_path))

    if copy_config:
        copy_from = os.path.join(script_dir, "config.yml")
        try:
            shutil.copy(copy_from, config_path)
        except shutil.Error as e:
            warnings.warn(
                "Error copying config file to user directory: {}".format(
                    e.strerror))

    # Copy style sheets to user directory
    styles_dir = os.path.join(user_dir, "styles")
    copy_style_sheets = True

    if os.path.isdir(styles_dir):
        copy_style_sheets = prompt(
            "Replace existing style sheets: {}".format(styles_dir))
        if copy_style_sheets:
            try:
                shutil.rmtree(styles_dir)
            except shutil.Error as e:
                warnings.warn(
                    "Error removing existing style sheets: {}".format(
                        e.strerror))

    if copy_style_sheets:
        try:
            copy_from = os.path.join(script_dir, "plotlib/styles")
            shutil.copytree(copy_from, styles_dir)
        except shutil.Error as e:
            warnings.warn(
                "Error copying style sheets to user directory: {}".format(
                    e.strerror))

    # Copy example data to user directory
    example_dir = os.path.join(user_dir, "example")
    copy_examples = True

    if os.path.isdir(example_dir):
        copy_examples = prompt(
            "Replace existing example files: {}".format(example_dir))
        if copy_examples:
            try:
                shutil.rmtree(example_dir)
            except shutil.Error as e:
                warnings.warn(
                    "Error removing existing example files: {}".format(
                        e.strerror))

    if copy_examples:
        try:
            copy_from = os.path.join(script_dir, "example")
            shutil.copytree(copy_from, example_dir)
        except shutil.Error as e:
            warnings.warn(
                "Error copying example files to user directory: {}".format(
                    e.strerror))
コード例 #10
0
ファイル: super_command.py プロジェクト: michaelhb/superplot
def __main__():
    """
    Parse plot options from command line arguments.
    """

    # Make parser for command line arguments

    parser = arg_parser(description='Superplot from command line', conflict_handler='resolve')

    parser.add_argument('txt_file',
                        help='*.txt file',
                        type=str)

    parser.add_argument('--plot_description',
                        help='Type of plot',
                        choices=PLOT_CLASS.keys(),
                        type=str,
                        default=None,
                        required=False)

    parser.add_argument('--info_file',
                        help='*.info file labelling *.txt file',
                        type=str,
                        default=None,
                        required=False)

    parser.add_argument('--output_file',
                        help='Name of output file for plot',
                        type=str,
                        default=None,
                        required=False)

    # Add everything else

    for attr in ATTRIBUTES:

        # Fetch default value
        try:
            default_ = default(attr)
        except KeyError:
            # Make sure plot elements are shown if unspecified
            if 'show' in attr:
                default_ = True
            else:
                default_ = None

        required = attr in COMPULSORY

        # Add to command line
        parser.add_argument('--{}'.format(attr),
                            required=required,
                            default=default_,
                            type=guess_type,
                            help='Superplot plot_option named tuple option')


    # Fetch arguments
    args = vars(parser.parse_args())

    # Make checks
    assert args['xindex'] >= 2, 'Must specify x-index >= 2 (e.g. --xindex=4)'
    assert args['yindex'] is None or args['yindex'] >= 2, 'If specified, y-index >= 2 (e.g. --yindex=4)'
    assert args['zindex'] is None or args['zindex'] >= 2, 'If specified, z-index >= 2 (e.g. --zindex=4)'

    if args['yindex'] is None:
        args['plot_description'] = ONE_DIM_PLOT

    if args['yindex'] and args['xindex'] and args['plot_description'] is None:
        args['plot_description'] = TWO_DIM_PLOT

    if args['yindex'] and args['xindex'] and args['zindex']:
        args['plot_description'] = THREE_DIM_PLOT

    assert args['plot_description'] in PLOT_CLASS.keys(), 'Unknown plot_description = {}'.format(args['plot_description'])

    # Make plot options

    plot_args = dict()
    for attr in ATTRIBUTES:
        plot_args[attr] = args[attr]

    options = plot_options(**plot_args)  # Convert dictionary to named tuple

    # Fetch options not inside named tuple

    txt_file = args['txt_file']
    info_file = args['info_file']
    plot_description = args['plot_description']
    output_file = args['output_file']

    # Make relevant plot

    save_plot(txt_file, info_file, output_file, plot_description, options)
コード例 #11
0
def main():
    parser = arg_parser(description='Superplot home directory setup', conflict_handler='resolve')

    parser.add_argument('--dir',
                        '-d',
                        help='Location of user home directory',
                        type=str,
                        required=True)

    args = vars(parser.parse_args())

    # Create target directory if it doesn't exist

    user_dir = os.path.abspath(args['dir'])
    try:
        if not os.path.isdir(user_dir):
            os.mkdir(user_dir)
    except OSError as e:
        warnings.warn(
            "Could not create home directory: {}".format(
                e.strerror
            )
        )
        sys.exit(1)

    # Drop text file with user home dir location in script directory
    script_dir = os.path.dirname(os.path.realpath(__file__))
    home_dir_file = os.path.join(script_dir, "user_home.txt")
    with open(home_dir_file, "wb") as f:
        f.write(user_dir)

    # Copy config.yml. Prompt user to overwrite if already present.
    config_path = os.path.join(user_dir, "config.yml")
    copy_config = True

    if os.path.exists(config_path):

        print "config.yml already present. Please note that versions of this file " \
              "distributed with previous versions of superplot may not work with " \
              "this release. If you wish to compare your customised config.yml with " \
              "the current defaults, an example is distributed with the source code " \
              "(superplot/config.yml)."

        copy_config = prompt("Replace existing file: {}".format(config_path))

    if copy_config:
        copy_from = os.path.join(script_dir, "config.yml")
        try:
            shutil.copy(copy_from, config_path)
        except shutil.Error as e:
            warnings.warn(
                    "Error copying config file to user directory: {}".format(
                            e.strerror
                    )
            )

    # Copy style sheets to user directory
    styles_dir = os.path.join(user_dir, "styles")
    copy_style_sheets = True

    if os.path.isdir(styles_dir):
        copy_style_sheets = prompt("Replace existing style sheets: {}".format(styles_dir))
        if copy_style_sheets:
            try:
                shutil.rmtree(styles_dir)
            except shutil.Error as e:
                warnings.warn(
                    "Error removing existing style sheets: {}".format(
                        e.strerror
                    )
                )

    if copy_style_sheets:
        try:
            copy_from = os.path.join(script_dir, "plotlib/styles")
            shutil.copytree(copy_from, styles_dir)
        except shutil.Error as e:
            warnings.warn(
                    "Error copying style sheets to user directory: {}".format(
                            e.strerror
                    )
            )

    # Copy example data to user directory
    example_dir = os.path.join(user_dir, "example")
    copy_examples = True

    if os.path.isdir(example_dir):
        copy_examples = prompt("Replace existing example files: {}".format(example_dir))
        if copy_examples:
            try:
                shutil.rmtree(example_dir)
            except shutil.Error as e:
                warnings.warn(
                    "Error removing existing example files: {}".format(
                        e.strerror
                    )
                )

    if copy_examples:
        try:
            copy_from = os.path.join(script_dir, "example")
            shutil.copytree(copy_from, example_dir)
        except shutil.Error as e:
            warnings.warn(
                    "Error copying example files to user directory: {}".format(
                            e.strerror
                    )
            )
コード例 #12
0
ファイル: super_command.py プロジェクト: freeboson/superplot
def __main__():
    """
    Parse plot options from command line arguments.
    """

    # Make parser for command line arguments

    parser = arg_parser(description='Superplot from command line',
                        conflict_handler='resolve')

    parser.add_argument('txt_file', help='*.txt file', type=str)

    parser.add_argument('--plot_description',
                        help='Type of plot',
                        choices=PLOT_CLASS.keys(),
                        type=str,
                        default=None,
                        required=False)

    parser.add_argument('--info_file',
                        help='*.info file labelling *.txt file',
                        type=str,
                        default=None,
                        required=False)

    parser.add_argument('--output_file',
                        help='Name of output file for plot',
                        type=str,
                        default=None,
                        required=False)

    # Add everything else

    for attr in ATTRIBUTES:

        # Fetch default value
        try:
            default_ = default(attr)
        except KeyError:
            # Make sure plot elements are shown if unspecified
            if 'show' in attr:
                default_ = True
            else:
                default_ = None

        required = attr in COMPULSORY

        # Add to command line
        parser.add_argument('--{}'.format(attr),
                            required=required,
                            default=default_,
                            type=guess_type,
                            help='Superplot plot_option named tuple option')

    # Fetch arguments
    args = vars(parser.parse_args())

    # Make checks
    assert args['xindex'] >= 2, 'Must specify x-index >= 2 (e.g. --xindex=4)'
    assert args['yindex'] is None or args[
        'yindex'] >= 2, 'If specified, y-index >= 2 (e.g. --yindex=4)'
    assert args['zindex'] is None or args[
        'zindex'] >= 2, 'If specified, z-index >= 2 (e.g. --zindex=4)'

    if args['yindex'] is None:
        args['plot_description'] = ONE_DIM_PLOT

    if args['yindex'] and args['xindex'] and args['plot_description'] is None:
        args['plot_description'] = TWO_DIM_PLOT

    if args['yindex'] and args['xindex'] and args['zindex']:
        args['plot_description'] = THREE_DIM_PLOT

    assert args['plot_description'] in PLOT_CLASS.keys(
    ), 'Unknown plot_description = {}'.format(args['plot_description'])

    # Make plot options

    plot_args = dict()
    for attr in ATTRIBUTES:
        plot_args[attr] = args[attr]

    options = plot_options(**plot_args)  # Convert dictionary to named tuple

    # Fetch options not inside named tuple

    txt_file = args['txt_file']
    info_file = args['info_file']
    plot_description = args['plot_description']
    output_file = args['output_file']

    # Make relevant plot

    save_plot(txt_file, info_file, output_file, plot_description, options)