当前位置: 首页>>代码示例>>Python>>正文


Python click.File方法代码示例

本文整理汇总了Python中click.File方法的典型用法代码示例。如果您正苦于以下问题:Python click.File方法的具体用法?Python click.File怎么用?Python click.File使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在click的用法示例。


在下文中一共展示了click.File方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: scan

# 需要导入模块: import click [as 别名]
# 或者: from click import File [as 别名]
def scan(self):
        logging.debug("Scanning %s" % self._path)
        if os.path.isfile(self._path):
            mime_type = magic.from_file(self._path, mime=True)
            self._files.append(File(self._path, mime_type))
            logging.debug('\t- full path: %s, mime_type: %s' % (os.path.abspath(self._path), mime_type))
        else:
            for root, subdirs, files in os.walk(self._path):
                for filename in files:
                    file_path = os.path.join(root, filename)
                    mime_type = magic.from_file(file_path, mime=True)

                    logging.debug('\t- full path: %s, mime_type: %s' % (file_path, mime_type))
                    self._files.append(File(file_path, mime_type))

        context = {'tokenizer': Tokenizer(), 'regex': RegexScanner(), 'ner': NERScanner()}
        for f in self._files:
            f.scan(context) 
开发者ID:tokern,项目名称:piicatcher,代码行数:20,代码来源:files.py

示例2: codegen_options

# 需要导入模块: import click [as 别名]
# 或者: from click import File [as 别名]
def codegen_options(f):
    f = click.option(
        "-c", "--categories", multiple=True, default=default_categories,
        type=click.Choice(all_categories),
        help="A list of the categories of inputs and outputs that should "
        "be enabled"
    )(f)
    f = click.option(
        "-f", "--param_file",
        type=click.File(),
        help="""YAML or JSON file describing the firmware module configuration to be flashed.
        This is the same file that is used for rosparam in the launch file."""
        "code"
    )(f)
    f = click.option(
        "-p", "--plugin", multiple=True, help="Enable a specific plugin"
    )(f)
    f = click.option(
        "-t", "--target", help="PlatformIO target (e.g.  upload)"
    )(f)
    f = click.option(
        "--status_update_interval", default=5,
        help="Minimum interval between driver status updates (in seconds)"
    )(f)
    return f 
开发者ID:OpenAgricultureFoundation,项目名称:openag_python,代码行数:27,代码来源:__init__.py

示例3: generate_config

# 需要导入模块: import click [as 别名]
# 或者: from click import File [as 别名]
def generate_config(ctx):
    """ Generates a sample gitlint config file. """
    path = click.prompt('Please specify a location for the sample gitlint config file', default=DEFAULT_CONFIG_FILE)
    path = os.path.realpath(path)
    dir_name = os.path.dirname(path)
    if not os.path.exists(dir_name):
        click.echo(u"Error: Directory '{0}' does not exist.".format(dir_name), err=True)
        ctx.exit(USAGE_ERROR_CODE)
    elif os.path.exists(path):
        click.echo(u"Error: File \"{0}\" already exists.".format(path), err=True)
        ctx.exit(USAGE_ERROR_CODE)

    LintConfigGenerator.generate_config(path)
    click.echo(u"Successfully generated {0}".format(path))
    ctx.exit(0)


# Let's Party! 
开发者ID:jorisroovers,项目名称:gitlint,代码行数:20,代码来源:cli.py

示例4: cli

# 需要导入模块: import click [as 别名]
# 或者: from click import File [as 别名]
def cli(output, akey, skey, sevs, last_found, cidr, tags, fields, verbose):
    '''
    Export -> CSV Writer

    Generates a CSV File from the vulnerability export using the fields
    specified.
    '''
    # Setup the logging verbosity.
    if verbose == 0:
        logging.basicConfig(level=logging.WARNING)
    if verbose == 1:
        logging.basicConfig(level=logging.INFO)
    if verbose > 1:
        logging.basicConfig(level=logging.DEBUG)
    
    # Instantiate the Tenable.io instance & initiate the vulnerability export.
    tio = TenableIO(akey, skey)
    vulns = tio.exports.vulns(last_found=last_found, severity=list(sevs), 
        cidr_range=cidr, tags=list(tags))
    
    # Pass everything to the CSV generator.
    total = export_vulns_to_csv(output, vulns, *fields)
    click.echo('Processed {} Vulnerabilities'.format(total)) 
开发者ID:tenable,项目名称:pyTenable,代码行数:25,代码来源:csvexport.py

示例5: read_config

# 需要导入模块: import click [as 别名]
# 或者: from click import File [as 别名]
def read_config(config_file, outfile, loglevel):
    """Parse the config file and print it to the output."""

    from genmod import logger
    from genmod.log import init_log
    init_log(logger, loglevel='DEBUG')

    logger.info("Reading Config File: {0}".format(config_file))

    config_reader = ConfigParser(config_file)

    for plugin in config_reader.plugins:
        logger.info("Found plugin:{0}".format(plugin))
        logger.info("{0}: {1}".format(
            plugin,config_reader.plugins[plugin])
            )

    for category in config_reader.categories:
        logger.info("Category {0}: {1}".format(
            category, config_reader.categories[category]
        )) 
开发者ID:moonso,项目名称:genmod,代码行数:23,代码来源:config_parser.py

示例6: gnql_command

# 需要导入模块: import click [as 别名]
# 或者: from click import File [as 别名]
def gnql_command(function):
    """Decorator that groups decorators common to gnql query and stats subcommands."""

    @click.command()
    @click.argument("query", required=False)
    @click.option("-k", "--api-key", help="Key to include in API requests")
    @click.option("-i", "--input", "input_file", type=click.File(), help="Input file")
    @click.option(
        "-o", "--output", "output_file", type=click.File(mode="w"), help="Output file"
    )
    @click.option(
        "-f",
        "--format",
        "output_format",
        type=click.Choice(["json", "txt", "xml"]),
        default="txt",
        help="Output format",
    )
    @click.option("-v", "--verbose", count=True, help="Verbose output")
    @pass_api_client
    @click.pass_context
    @echo_result
    @handle_exceptions
    @functools.wraps(function)
    def wrapper(*args, **kwargs):
        return function(*args, **kwargs)

    return wrapper 
开发者ID:GreyNoise-Intelligence,项目名称:pygreynoise,代码行数:30,代码来源:decorator.py

示例7: ip_lookup_command

# 需要导入模块: import click [as 别名]
# 或者: from click import File [as 别名]
def ip_lookup_command(function):
    """Decorator that groups decorators common to ip and quick subcommand."""

    @click.command()
    @click.argument("ip_address", callback=ip_addresses_parameter, nargs=-1)
    @click.option("-k", "--api-key", help="Key to include in API requests")
    @click.option("-i", "--input", "input_file", type=click.File(), help="Input file")
    @click.option(
        "-o", "--output", "output_file", type=click.File(mode="w"), help="Output file"
    )
    @click.option(
        "-f",
        "--format",
        "output_format",
        type=click.Choice(["json", "txt", "xml"]),
        default="txt",
        help="Output format",
    )
    @pass_api_client
    @click.pass_context
    @echo_result
    @handle_exceptions
    @functools.wraps(function)
    def wrapper(*args, **kwargs):
        return function(*args, **kwargs)

    return wrapper 
开发者ID:GreyNoise-Intelligence,项目名称:pygreynoise,代码行数:29,代码来源:decorator.py

示例8: get_ip_addresses

# 需要导入模块: import click [as 别名]
# 或者: from click import File [as 别名]
def get_ip_addresses(context, input_file, ip_address):
    """Get IP addresses passed as argument or via input file.

    :param context: Subcommand context
    :type context: click.Context
    :param input_file: Input file
    :type input_file: click.File | None
    :param ip_address: IP addresses passed via the ip address argument
    :type query: tuple(str, ...)

    """
    if input_file is None and not sys.stdin.isatty():
        input_file = click.open_file("-")

    if input_file is None and not ip_address:
        click.echo(context.get_help())
        context.exit(-1)

    ip_addresses = []
    if input_file is not None:
        lines = [line.strip() for line in input_file]
        ip_addresses.extend([line for line in lines if validate_ip(line, strict=False)])
    ip_addresses.extend(list(ip_address))

    if not ip_addresses:
        output = [
            context.command.get_usage(context),
            (
                "Error: at least one valid IP address must be passed either as an "
                "argument (IP_ADDRESS) or through the -i/--input_file option."
            ),
        ]
        click.echo("\n\n".join(output))
        context.exit(-1)

    return ip_addresses 
开发者ID:GreyNoise-Intelligence,项目名称:pygreynoise,代码行数:38,代码来源:helper.py

示例9: get_queries

# 需要导入模块: import click [as 别名]
# 或者: from click import File [as 别名]
def get_queries(context, input_file, query):
    """Get queries passed as argument or via input file.

    :param context: Subcommand context
    :type context: click.Context
    :param input_file: Input file
    :type input_file: click.File | None
    :param query: GNQL query
    :type query: str | None

    """
    if input_file is None and not sys.stdin.isatty():
        input_file = click.open_file("-")

    if input_file is None and not query:
        click.echo(context.get_help())
        context.exit(-1)

    queries = []
    if input_file is not None:
        queries.extend([line.strip() for line in input_file])
    if query:
        queries.append(query)

    if not queries:
        output = [
            context.command.get_usage(context),
            (
                "Error: at least one query must be passed either as an argument "
                "(QUERY) or through the -i/--input_file option."
            ),
        ]
        click.echo("\n\n".join(output))
        context.exit(-1)

    return queries 
开发者ID:GreyNoise-Intelligence,项目名称:pygreynoise,代码行数:38,代码来源:helper.py

示例10: report_data_file_cb

# 需要导入模块: import click [as 别名]
# 或者: from click import File [as 别名]
def report_data_file_cb(ctx, param, value):
    """Use click.File for data_file only if it is used, to prevent an error
    if it does not exist (click tries to open it always)."""
    if ctx.params.get('profile_file', ()):
        return value
    return click.File('r').convert(value, param, ctx) 
开发者ID:Vimjas,项目名称:covimerage,代码行数:8,代码来源:cli.py

示例11: __init__

# 需要导入模块: import click [as 别名]
# 或者: from click import File [as 别名]
def __init__(self, name, mime_type):
        super(File, self).__init__(name, (), ())
        self._mime_type = mime_type 
开发者ID:tokern,项目名称:piicatcher,代码行数:5,代码来源:files.py

示例12: dispatch

# 需要导入模块: import click [as 别名]
# 或者: from click import File [as 别名]
def dispatch(cls, ns):
        logging.debug("File Dispatch entered")
        explorer = cls(ns)
        explorer.scan()

        if ns.catalog['format'] == "ascii_table":
            headers = ["Path", "Mime/Type", "pii"]
            tableprint.table(explorer.get_tabular(), headers)
        elif ns.catalog['format'] == "json":
            FileStore.save_schemas(explorer) 
开发者ID:tokern,项目名称:piicatcher,代码行数:12,代码来源:files.py

示例13: tts_cli

# 需要导入模块: import click [as 别名]
# 或者: from click import File [as 别名]
def tts_cli(text, file, output, slow, lang, nocheck):
    """ Read <text> to mp3 format using Google Translate's Text-to-Speech API
    (set <text> or --file <file> to - for standard input)
    """

    # stdin for <text>
    if text == '-':
        text = click.get_text_stream('stdin').read()

    # stdout (when no <output>)
    if not output:
        output = click.get_binary_stream('stdout')

    # <file> input (stdin on '-' is handled by click.File)
    if file:
        try:
            text = file.read()
        except UnicodeDecodeError as e:  # pragma: no cover
            log.debug(str(e), exc_info=True)
            raise click.FileError(
                file.name,
                "<file> must be encoded using '%s'." %
                sys_encoding())

    # TTS
    try:
        tts = gTTS(
            text=text,
            lang=lang,
            slow=slow,
            lang_check=not nocheck)
        tts.write_to_fp(output)
    except (ValueError, AssertionError) as e:
        raise click.UsageError(str(e))
    except gTTSError as e:
        raise click.ClickException(str(e)) 
开发者ID:luoliyan,项目名称:chinese-support-redux,代码行数:38,代码来源:cli.py

示例14: lsusb

# 需要导入模块: import click [as 别名]
# 或者: from click import File [as 别名]
def lsusb(cfg):
    if len(prosflasher.ports.list_com_ports()) == 0 or prosflasher.ports.list_com_ports() is None:
        click.echo('No serial ports found.')
    else:
        click.echo('Available Ports:')
        click.echo(prosflasher.ports.create_port_list(cfg.verbosity > 0))


# @flasher_cli.command(name='dump-cortex', short_help='Dumps user flash contents to a specified file')
# @click.option('-v', '--verbose', is_flag=True)
# @click.argument('file', default=sys.stdout, type=click.File())
# def dump_cortex(file, verbose):
#     pass 
开发者ID:purduesigbots,项目名称:pros-cli2,代码行数:15,代码来源:flasher.py

示例15: file

# 需要导入模块: import click [as 别名]
# 或者: from click import File [as 别名]
def file(ctx, data_dir, data_file):
    """Use the File SWAG Backend"""
    if not ctx.file:
        ctx.data_file = data_file

    if not ctx.data_dir:
        ctx.data_dir = data_dir

    ctx.type = 'file' 
开发者ID:Netflix-Skunkworks,项目名称:swag-client,代码行数:11,代码来源:cli.py


注:本文中的click.File方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。