本文整理汇总了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)
示例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
示例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!
示例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))
示例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]
))
示例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
示例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
示例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
示例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
示例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)
示例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
示例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)
示例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))
示例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
示例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'