本文整理匯總了Python中click.get_text_stream方法的典型用法代碼示例。如果您正苦於以下問題:Python click.get_text_stream方法的具體用法?Python click.get_text_stream怎麽用?Python click.get_text_stream使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類click
的用法示例。
在下文中一共展示了click.get_text_stream方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: encode
# 需要導入模塊: import click [as 別名]
# 或者: from click import get_text_stream [as 別名]
def encode(precision, with_z):
"""Given GeoJSON on stdin, writes a geobuf file to stdout."""
logger = logging.getLogger('geobuf')
stdin = click.get_text_stream('stdin')
sink = click.get_binary_stream('stdout')
try:
data = json.load(stdin)
pbf = geobuf.encode(
data,
precision if precision >= 0 else 6,
3 if with_z else 2)
sink.write(pbf)
sys.exit(0)
except Exception:
logger.exception("Failed. Exception caught")
sys.exit(1)
示例2: validate_text
# 需要導入模塊: import click [as 別名]
# 或者: from click import get_text_stream [as 別名]
def validate_text(ctx, param, value):
conf = click.get_current_context().obj["conf"]
if isinstance(value, tuple):
value = " ".join(value)
if not value and not sys.stdin.isatty():
value = click.get_text_stream("stdin").read()
if value:
value = value.strip()
if conf.character_warning and len(value) > conf.character_warning:
click.confirm("✂ Warning: Tweet is longer than {0} characters. Are you sure?".format(
conf.character_warning), abort=True)
return value
else:
raise click.BadArgumentUsage("Text can’t be empty.")
示例3: _notify
# 需要導入模塊: import click [as 別名]
# 或者: from click import get_text_stream [as 別名]
def _notify(p, **data):
"""The callback func that will be hooked to the ``notify`` command"""
message = data.get("message")
if not message and not sys.stdin.isatty():
message = click.get_text_stream("stdin").read()
data["message"] = message
data = clean_data(data)
ctx = click.get_current_context()
if ctx.obj.get("env_prefix"):
data["env_prefix"] = ctx.obj["env_prefix"]
rsp = p.notify(**data)
rsp.raise_on_errors()
click.secho(f"Succesfully sent a notification to {p.name}!", fg="green")
示例4: main
# 需要導入模塊: import click [as 別名]
# 或者: from click import get_text_stream [as 別名]
def main(**options):
"""Slurp up linter output and send it to a GitHub PR review."""
configure_logging(log_all=options.get('log'))
stdin_stream = click.get_text_stream('stdin')
stdin_text = stdin_stream.read()
click.echo(stdin_text)
config = Config(options)
build = LintlyBuild(config, stdin_text)
try:
build.execute()
except NotPullRequestException:
logger.info('Not a PR. Lintly is exiting.')
sys.exit(0)
exit_code = 0
# Exit with the number of files that have violations
if not options['exit_zero']:
exit_code = len(build.violations)
sys.exit(exit_code)
示例5: decrypt
# 需要導入模塊: import click [as 別名]
# 或者: from click import get_text_stream [as 別名]
def decrypt(private_key, public_key, nonce):
# Get key instances
private_key = util.read_key_or_key_file(private_key, Key.Type.private)
public_key = util.read_key_or_key_file(public_key, Key.Type.public)
# Convert nonce to bytes
nonce = binascii.unhexlify(nonce)
# Read message from stdin and convert to bytes
message = click.get_text_stream('stdin').read()
message = binascii.unhexlify(message)
# Unpack message
connection = _MockConnection(private_key, public_key)
parameters = {'from_id': '', 'message_id': '', 'date': ''}
message = yield from e2e.Message.receive(connection, parameters, nonce, message)
# Ensure that this is a text message
if message.type is not e2e.Message.Type.text_message:
raise TypeError('Cannot decrypt message type {} in CLI'.format(message.type))
# Print text
click.echo()
click.echo(message.text)
示例6: send_simple
# 需要導入模塊: import click [as 別名]
# 或者: from click import get_text_stream [as 別名]
def send_simple(ctx, **arguments):
# Read message from stdin
text = click.get_text_stream('stdin').read().strip()
# Create connection
with Connection(arguments['from'], arguments['secret'], **ctx.obj) as connection:
# Create message
message = simple.TextMessage(
connection=connection,
to_id=arguments['to'],
text=text
)
# Send message
click.echo()
click.echo((yield from message.send()))
示例7: process_url
# 需要導入模塊: import click [as 別名]
# 或者: from click import get_text_stream [as 別名]
def process_url(ctx, param, value):
if value == "-":
stdin_text = click.get_text_stream("stdin")
if not stdin_text.isatty():
value = stdin_text.read().strip()
else:
raise CliError("No input received from stdin")
if "://" not in value:
if ctx.info_name != "cast":
raise CliError("Local file not allowed as argument to this command")
if not Path(value).is_file():
raise CliError("The chosen file does not exist")
return value
示例8: sign
# 需要導入模塊: import click [as 別名]
# 或者: from click import get_text_stream [as 別名]
def sign(ctx, file, account):
""" Sign a message with an account
"""
if not file:
print_message("Prompting for message. Terminate with CTRL-D", "info")
file = click.get_text_stream("stdin")
m = Message(file.read(), bitshares_instance=ctx.bitshares)
print_message(m.sign(account), "info")
示例9: verify
# 需要導入模塊: import click [as 別名]
# 或者: from click import get_text_stream [as 別名]
def verify(ctx, file, account):
""" Verify a signed message
"""
if not file:
print_message("Prompting for message. Terminate with CTRL-D", "info")
file = click.get_text_stream("stdin")
m = Message(file.read(), bitshares_instance=ctx.bitshares)
try:
if m.verify():
print_message("Verified", "success")
else:
print_message("not verified", "error")
except InvalidMessageSignature:
print_message("Signature INVALID!", "error")
示例10: test_confirm_destructive_query_notty
# 需要導入模塊: import click [as 別名]
# 或者: from click import get_text_stream [as 別名]
def test_confirm_destructive_query_notty():
stdin = click.get_text_stream("stdin")
if not stdin.isatty():
sql = "drop database foo;"
assert confirm_destructive_query(sql) is None
示例11: process_pipeline
# 需要導入模塊: import click [as 別名]
# 或者: from click import get_text_stream [as 別名]
def process_pipeline(processors, encoding, **kwargs):
with click.get_text_stream("stdin", encoding=encoding) as fin:
iterator = fin # Initialize fin as the first iterator.
for proc in processors:
iterator = proc(list(iterator), **kwargs)
if iterator:
for item in iterator:
click.echo(item)
示例12: decode
# 需要導入模塊: import click [as 別名]
# 或者: from click import get_text_stream [as 別名]
def decode():
"""Given a Geobuf byte string on stdin, write a GeoJSON feature
collection to stdout."""
logger = logging.getLogger('geobuf')
stdin = click.get_binary_stream('stdin')
sink = click.get_text_stream('stdout')
try:
pbf = stdin.read()
data = geobuf.decode(pbf)
json.dump(data, sink)
sys.exit(0)
except Exception:
logger.exception("Failed. Exception caught")
sys.exit(1)
示例13: tts_cli
# 需要導入模塊: import click [as 別名]
# 或者: from click import get_text_stream [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: __init__
# 需要導入模塊: import click [as 別名]
# 或者: from click import get_text_stream [as 別名]
def __init__(self, stream=None, symbols=None, title=None):
if symbols is None:
symbols = list(self._default_symbols)
if stream is None:
stream = click.get_text_stream('stdout')
self.symbol_cycle = itertools.cycle(symbols)
self.stream = stream
self.title = title
示例15: msms_intervals
# 需要導入模塊: import click [as 別名]
# 或者: from click import get_text_stream [as 別名]
def msms_intervals(paths, processes=4, time_radius=5, mz_lower=2., mz_higher=3., output=None):
'''Construct an interval tree spanning time and m/z domains where MSn spectra were acquired
in the LC-MS map. The interval tree is serialized to JSON.
'''
interval_extraction = _MSMSIntervalTask(time_radius, mz_lower, mz_higher)
interval_set = []
total_work_items = len(paths) * processes * 4
def _run():
for path in paths:
reader = MSFileLoader(path)
chunk_out_of_order = quick_index.run_task_in_chunks(
reader, processes, processes * 4, task=interval_extraction)
for chunk in chunk_out_of_order:
interval_set.extend(chunk)
yield 0
work_iterator = _run()
with click.progressbar(work_iterator, length=total_work_items, label='Extracting Intervals') as g:
for _ in g:
pass
tree = scan_interval_tree.ScanIntervalTree(scan_interval_tree.make_rt_tree(interval_set))
if output is not None:
with open(output, 'wt') as fh:
tree.serialize(fh)
else:
stream = click.get_text_stream('stdout')
tree.serialize(stream)
stream.flush()