當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。