Python click 模块,STRING 实例源码
我们从Python开源项目中,提取了以下21个代码示例,用于说明如何使用click.STRING。
def convert_param_to_option(self, parameter):
"""
Convert a Parameter into a click Option.
:type parameter: valohai_yaml.objs.Parameter
:rtype: click.Option
"""
assert isinstance(parameter, Parameter)
option = click.Option(
param_decls=[
'--%s' % parameter.name.replace('_', '-'),
],
required=(parameter.default is None and not parameter.optional),
default=parameter.default,
help=parameter.description,
type=self.parameter_type_map.get(parameter.type, click.STRING),
)
option.name = '~%s' % parameter.name # Tildify so we can pick these out of kwargs easily
return option
def add(license_name, author, year):
"""Tries to find a license that matches the given LICENSE argument. If one exists and
takes a author and year,it adds them to the license. Otherwise it writes the license
without an author and year and informs the user.
:param license_name: the 'human' name of the license that should be added. Notary will
try to guess the actual name from this.
:param author: Tuple representing the name of the author.
:param year: Integer representing the year that will be written to the license.
"""
ensure_no_license_files()
if not license_name:
license_name = click.prompt("License name", type=click.STRING)
guesses = utils.guess_license(name=license_name)
if len(guesses) > 1:
cls = choose_license(guesses, author=author, year=year)
else:
cls = guesses[0]
if cls.author_placeholder and not author:
click.echo("{0} requires an author.".format(yellow(cls.name)))
author = click.prompt("Author", type=click.STRING)
lic = cls(author=author, year=year)
if click.confirm("Adding {0} as the project's license. Continue?".format(yellow(lic.name))):
with LICENSE_FILE.open('w') as f:
f.write(lic.content)
click.echo(
"Added {0} to {1}.".format(yellow(lic.name), green(str(LICENSE_FILE.absolute())))
)
def test_click():
import click
try:
@click.command()
@click.argument("arg1", required=True, autocompletion=["foo", "bar"])
def command_test(arg1):
pass
except TypeError as err:
if err.message == "__init__() got an unexpected keyword argument 'autocompletion'":
raise TypeError("Wrong version of click installed. Please install https://github.com/cbandera/click.git.")
def query_user(self, data, category):
"""
For every entry in dict,prompt user to accept default value or specify custom input.
:param data: Dictionary
:param category: Name to print to console before prompts.
:return: Filled Dictionary
"""
click.echo("\n==" + str(category) + "==")
for k, v in data.iteritems():
if type(v) is OrderedDict:
# If dict contains nested dicts -> recurse
data[k] = self.query_user(data[k], k)
continue
elif k == "LastModified":
# Wo kNow this,do not ask user
data[k] = time.asctime()
continue
elif k == "MetaDataVersion":
continue # Use template version
elif k == "CreatedBy":
# Get user name as default value
v = getpass.getuser()
# We use the decode and unidecode functions to get rid of any non ascii signs,that Could lead to trouble
# later on.
data[k] = unidecode(click.prompt(k, default=str(v).decode("utf-8"), type=click.STRING))
return data
def cli(ctx, host, port, user, password, ssl, request_password, authentication, server_info, metrics, debug):
"""LDAP for humans"""
if request_password and not password:
password = click.prompt('Password <will not be shown>', hide_input=True, type=click.STRING)
if ssl and not port:
port = 636
elif not port:
port = 389
ctx.obj = Session(host, debug)
def endpoint_argument(f):
return click.option(
'--host', '-H', default=False,
type=click.STRING,
help='BDocker server endpoint'
)(f)
def token_argument(f):
return click.argument('token',
type=click.STRING
)(f)
def token_option(f):
return click.option(
'--token', '-t', default=None, help='The token ID'
)(f)
def source_argument(f):
return click.argument('source',
type=click.STRING
)(f)
def container_id_argument(f):
return click.argument("container_id",
type=click.STRING
)(f)
def image_id_argument(f):
return click.argument("image_id",
type=click.STRING
)(f)
def command_argument(f):
return click.argument("script",
type=click.STRING
)(f)
def user_option(f):
return click.option(
'--user', '-u', help='User name'
)(f)
def volume_option(f):
return click.option(
'--volume', '-v', callback=parse_volume,
help='Bind mount a volume'
)(f)
def path_argument_dest(f):
return click.argument("path_dest",
type=click.STRING,
callback=parse_cp_path
)(f)
def path_argument(f):
return click.argument("path", nargs=2,
callback=parse_cp_path
)(f)
def test_str_type(self):
class Option(StringOption):
Metadata = 'name'
cli = ['--name']
click_option = ClickObjectOption(Option)
self.assertEqual(click_option.type, click.STRING)
def collect_Metadata(self, filename=MetaDATA_CACHE, clean_start=False, reuse_last=False):
"""
Creates new Metadata stub from template and updates it from data found in filename.
Afterwards it will prompt the user to confirm entries and to add additional ones.
:param filename: Path to file or rosbag with existing data
:param clean_start: Do not use old data
:return: None,data is stored in member variable
"""
new_data = self.load_from_file(MetaDATA_TEMPLATE)
if not clean_start:
last_data = OrderedDict()
if os.path.isfile(filename):
if filename.endswith(".bag"):
last_data = self.load_from_bag(filename)
# Keep all of the old data
new_data.update(last_data)
else:
last_data = self.load_from_file(filename)
try:
if str(last_data["General"]["MetaDataVers"]) != str(new_data["General"]["MetaDataVers"]):
click.secho("Wrong Version Number detected,dropping old data.", fg="yellow")
last_data = OrderedDict()
except KeyError:
pass
if last_data:
new_data = self.update_data(new_data, last_data)
if not reuse_last:
new_data = self.query_user(new_data, "Please provide information about this rosbag.")
try:
click.echo("Add additional fields Now or continue by pressing Ctrl+d")
while True:
k = unidecode(click.prompt('Field name', type=click.STRING))
v = unidecode(click.prompt(k, type=click.STRING))
if "Custom" not in new_data:
new_data["Custom"] = OrderedDict()
new_data["Custom"][k] = v
except click.Abort:
click.echo("")
self.data = new_data
self.write_to_file(MetaDATA_CACHE, new_data)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。