本文整理汇总了Python中click.open_file方法的典型用法代码示例。如果您正苦于以下问题:Python click.open_file方法的具体用法?Python click.open_file怎么用?Python click.open_file使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类click
的用法示例。
在下文中一共展示了click.open_file方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: analyze
# 需要导入模块: import click [as 别名]
# 或者: from click import open_file [as 别名]
def analyze(
context, api_client, api_key, input_file, output_file, output_format, verbose
):
"""Analyze the IP addresses in a log file, stdin, etc."""
if input_file is None:
if sys.stdin.isatty():
output = [
context.command.get_usage(context),
(
"Error: at least one text file must be passed "
"either through the -i/--input_file option or through a shell pipe."
),
]
click.echo("\n\n".join(output))
context.exit(-1)
else:
input_file = click.open_file("-")
if output_file is None:
output_file = click.open_file("-", mode="w")
result = api_client.analyze(input_file)
return result
示例2: filter
# 需要导入模块: import click [as 别名]
# 或者: from click import open_file [as 别名]
def filter(context, api_client, api_key, input_file, output_file, noise_only):
"""Filter the noise from a log file, stdin, etc."""
if input_file is None:
if sys.stdin.isatty():
output = [
context.command.get_usage(context),
(
"Error: at least one text file must be passed "
"either through the -i/--input_file option or through a shell pipe."
),
]
click.echo("\n\n".join(output))
context.exit(-1)
else:
input_file = click.open_file("-")
if output_file is None:
output_file = click.open_file("-", mode="w")
for chunk in api_client.filter(input_file, noise_only=noise_only):
output_file.write(ANSI_MARKUP(chunk))
示例3: synthesize
# 需要导入模块: import click [as 别名]
# 或者: from click import open_file [as 别名]
def synthesize(access_key, secret_key, output_file, voice_name, voice_language,
codec, text):
"""Synthesize passed text and save it as an audio file"""
try:
ivona_api = IvonaAPI(
access_key, secret_key,
voice_name=voice_name, language=voice_language, codec=codec,
)
except (ValueError, IvonaAPIException) as e:
raise click.ClickException("Something went wrong: {}".format(repr(e)))
with click.open_file(output_file, 'wb') as file:
ivona_api.text_to_speech(text, file)
click.secho(
"File successfully saved as '{}'".format(output_file),
fg='green',
)
示例4: list
# 需要导入模块: import click [as 别名]
# 或者: from click import open_file [as 别名]
def list(ctx, output):
"""List datasets.
Prints a list of objects describing datasets.
$ mapbox datasets list
All endpoints require authentication. An access token with
`datasets:read` scope is required, see `mapbox --help`.
"""
stdout = click.open_file(output, 'w')
service = ctx.obj.get('service')
res = service.list()
if res.status_code == 200:
click.echo(res.text, file=stdout)
else:
raise MapboxCLIException(res.text.strip())
示例5: read_dataset
# 需要导入模块: import click [as 别名]
# 或者: from click import open_file [as 别名]
def read_dataset(ctx, dataset, output):
"""Read the attributes of a dataset.
Prints a JSON object containing the attributes
of a dataset. The attributes: owner (a Mapbox account),
id (dataset id), created (Unix timestamp), modified
(timestamp), name (string), and description (string).
$ mapbox datasets read-dataset dataset-id
All endpoints require authentication. An access token with
`datasets:read` scope is required, see `mapbox --help`.
"""
stdout = click.open_file(output, 'w')
service = ctx.obj.get('service')
res = service.read_dataset(dataset)
if res.status_code == 200:
click.echo(res.text, file=stdout)
else:
raise MapboxCLIException(res.text.strip())
示例6: list_features
# 需要导入模块: import click [as 别名]
# 或者: from click import open_file [as 别名]
def list_features(ctx, dataset, reverse, start, limit, output):
"""Get features of a dataset.
Prints the features of the dataset as a GeoJSON feature collection.
$ mapbox datasets list-features dataset-id
All endpoints require authentication. An access token with
`datasets:read` scope is required, see `mapbox --help`.
"""
stdout = click.open_file(output, 'w')
service = ctx.obj.get('service')
res = service.list_features(dataset, reverse, start, limit)
if res.status_code == 200:
click.echo(res.text, file=stdout)
else:
raise MapboxCLIException(res.text.strip())
示例7: read_feature
# 需要导入模块: import click [as 别名]
# 或者: from click import open_file [as 别名]
def read_feature(ctx, dataset, fid, output):
"""Read a dataset feature.
Prints a GeoJSON representation of the feature.
$ mapbox datasets read-feature dataset-id feature-id
All endpoints require authentication. An access token with
`datasets:read` scope is required, see `mapbox --help`.
"""
stdout = click.open_file(output, 'w')
service = ctx.obj.get('service')
res = service.read_feature(dataset, fid)
if res.status_code == 200:
click.echo(res.text, file=stdout)
else:
raise MapboxCLIException(res.text.strip())
示例8: idzip_compression
# 需要导入模块: import click [as 别名]
# 或者: from click import open_file [as 别名]
def idzip_compression(path, output):
'''Compress a file using idzip, a gzip-compatible format with random access support.
'''
if output is None:
output = '-'
with click.open_file(output, mode='wb') as outfh:
writer = _compression.GzipFile(fileobj=outfh, mode='wb')
with click.open_file(path, 'rb') as infh:
try:
infh_wrap = io.BufferedReader(infh)
header = infh_wrap.peek(2)
if _compression.starts_with_gz_magic(header):
click.echo("Detected gzip input file", err=True)
infh_wrap = _compression.GzipFile(fileobj=infh_wrap)
except AttributeError:
infh_wrap = infh
buffer_size = _compression.WRITE_BUFFER_SIZE
chunk = infh_wrap.read(buffer_size)
while chunk:
writer.write(chunk)
chunk = infh_wrap.read(buffer_size)
writer.close()
示例9: save_cmd
# 需要导入模块: import click [as 别名]
# 或者: from click import open_file [as 别名]
def save_cmd(filename, indent, textures):
"""Save the city model to a CityJSON file."""
def processor(cm):
print_cmd_status("Saving CityJSON to a file (%s)" % (filename))
f = os.path.basename(filename)
d = os.path.abspath(os.path.dirname(filename))
if not os.path.isdir(d):
os.makedirs(d)
p = os.path.join(d, f)
try:
fo = click.open_file(p, mode='w')
if textures:
cm.copy_textures(textures, p)
if indent == 0:
json_str = json.dumps(cm.j, separators=(',',':'))
fo.write(json_str)
else:
json_str = json.dumps(cm.j, indent=indent)
fo.write(json_str)
except IOError as e:
raise click.ClickException('Invalid output file: "%s".\n%s' % (p, e))
return cm
return processor
示例10: rename
# 需要导入模块: import click [as 别名]
# 或者: from click import open_file [as 别名]
def rename(workspace, output_file, channel, sample, modifier, measurement):
"""
Rename components of the workspace.
See :func:`pyhf.workspace.Workspace.rename` for more information.
"""
with click.open_file(workspace, 'r') as specstream:
spec = json.load(specstream)
ws = Workspace(spec)
renamed_ws = ws.rename(
channels=dict(channel),
samples=dict(sample),
modifiers=dict(modifier),
measurements=dict(measurement),
)
if output_file is None:
click.echo(json.dumps(renamed_ws, indent=4, sort_keys=True))
else:
with open(output_file, 'w+') as out_file:
json.dump(renamed_ws, out_file, indent=4, sort_keys=True)
log.debug("Written to {0:s}".format(output_file))
示例11: combine
# 需要导入模块: import click [as 别名]
# 或者: from click import open_file [as 别名]
def combine(workspace_one, workspace_two, join, output_file):
"""
Combine two workspaces into a single workspace.
See :func:`pyhf.workspace.Workspace.combine` for more information.
"""
with click.open_file(workspace_one, 'r') as specstream:
spec_one = json.load(specstream)
with click.open_file(workspace_two, 'r') as specstream:
spec_two = json.load(specstream)
ws_one = Workspace(spec_one)
ws_two = Workspace(spec_two)
combined_ws = Workspace.combine(ws_one, ws_two, join=join)
if output_file is None:
click.echo(json.dumps(combined_ws, indent=4, sort_keys=True))
else:
with open(output_file, 'w+') as out_file:
json.dump(combined_ws, out_file, indent=4, sort_keys=True)
log.debug("Written to {0:s}".format(output_file))
示例12: verify
# 需要导入模块: import click [as 别名]
# 或者: from click import open_file [as 别名]
def verify(background_only, patchset):
"""
Verify the patchset digests against a background-only workspace specification. Verified if no exception was raised.
Raises:
:class:`~pyhf.exceptions.PatchSetVerificationError`: if the patchset cannot be verified against the workspace specification
Returns:
None
"""
with click.open_file(background_only, 'r') as specstream:
spec = json.load(specstream)
ws = Workspace(spec)
with click.open_file(patchset, 'r') as fstream:
patchset_spec = json.load(fstream)
patchset = PatchSet(patchset_spec)
patchset.verify(ws)
click.echo("All good.")
示例13: do_invoke
# 需要导入模块: import click [as 别名]
# 或者: from click import open_file [as 别名]
def do_invoke(template, namespace, function, env_vars, event, no_event, debug_port, debug_args, quiet):
if no_event:
event_data = "{}"
else:
Operation('Enter an event:', color="green").echo()
with click.open_file(event, 'r', encoding="utf-8") as f:
event_data = f.read()
try:
with InvokeContext(
template_file=template,
namespace=namespace,
function=function,
env_file=env_vars,
debug_port=debug_port,
debug_args=debug_args,
event=event_data,
is_quiet=quiet
) as context:
context.invoke()
except Exception as e:
Operation(e, err_msg=traceback.format_exc(), level="ERROR").no_output()
raise e
示例14: append_errors_to_file
# 需要导入模块: import click [as 别名]
# 或者: from click import open_file [as 别名]
def append_errors_to_file(filename:str, errors:List[Error], time) -> None:
"""
Creates a single file that logs all errors
"""
dirname = os.path.dirname(filename)
if dirname != '':
os.makedirs(dirname, exist_ok=True)
with click.open_file(filename, 'a+') as f:
f.write('--- {} ---\n'.format(time))
for e in errors:
if isinstance(e, NodeError):
f.write('node({})\t{}\n'.format(e.node, e.message))
elif isinstance(e, EdgeError):
f.write('edge({}, {})\t{}\n'.format(e.subject, e.object, e.message))
else:
raise Exception('Expected type {} but got: {}'.format(Error, type(error)))
click.echo('Logged {} errors to {}'.format(len(errors), filename))
示例15: write_output_file
# 需要导入模块: import click [as 别名]
# 或者: from click import open_file [as 别名]
def write_output_file(config, domains_combined):
config_dict = make_config_dict()
leprint("Writing output file: %s in %s format", config.output, config.mode,
level=LOG['INFO'])
with click.open_file(config.output, 'wb', atomic=True, lazy=True) as fh:
fh.write(make_output_file_header(config_dict))
for domain in domains_combined:
if config.mode == 'dnsmasq':
if config.dest_ip:
dnsmasq_line = 'address=/.' + domain.decode('utf8') + \
'/' + config.dest_ip + '\n'
else:
dnsmasq_line = 'server=/.' + domain.decode('utf8') + \
'/' '\n' # return NXDOMAIN
fh.write(dnsmasq_line.encode('utf8'))
elif config.mode == 'hosts':
if config.dest_ip:
hosts_line = config.dest_ip + ' ' + domain.decode('utf8') + '\n'
else:
hosts_line = '127.0.0.1' + ' ' + domain.decode('utf8') + '\n'
fh.write(hosts_line.encode('utf8'))