本文整理匯總了Python中click.Path方法的典型用法代碼示例。如果您正苦於以下問題:Python click.Path方法的具體用法?Python click.Path怎麽用?Python click.Path使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類click
的用法示例。
在下文中一共展示了click.Path方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: load_config
# 需要導入模塊: import click [as 別名]
# 或者: from click import Path [as 別名]
def load_config(func):
"""Decorator for add load config file option"""
@functools.wraps(func)
def internal(*args, **kwargs):
filename = kwargs.pop('config')
if filename is None:
click.echo('--config option is required.', err=True)
raise SystemExit(1)
config = load(pathlib.Path(filename))
kwargs['config'] = config
return func(*args, **kwargs)
decorator = click.option(
'--config',
'-c',
type=click.Path(exists=True),
envvar='YUI_CONFIG_FILE_PATH',
)
return decorator(internal)
示例2: load_dotenv_if_exists
# 需要導入模塊: import click [as 別名]
# 或者: from click import Path [as 別名]
def load_dotenv_if_exists(self) -> None:
if os.environ.get("QUART_SKIP_DOTENV") == "1":
return
if not Path(".env").is_file() and not Path(".quartenv").is_file():
return
try:
if Path(".env").is_file():
load_dotenv()
if Path(".quartenv").is_file():
load_dotenv(dotenv_path=Path(".") / ".quartenv")
except NameError:
print( # noqa: T001, T002
"* Tip: There are .env files present. "
'Do "pip install python-dotenv" to use them.'
)
示例3: save_and_exit
# 需要導入模塊: import click [as 別名]
# 或者: from click import Path [as 別名]
def save_and_exit(self):
# write report file
rows_all, rows_clean = [], []
for f in self.images:
row = (f.image_path, f.label if f.label else "?")
if f.label is not "d":
rows_clean.append(row)
rows_all.append(row)
for ftype, rows in zip(["all", "clean"], [rows_all, rows_clean]):
foutname = Path(
str(self.infolder).replace(" ", "_") + f"_report_{ftype}.csv"
)
with open(foutname, "w") as f:
f.write("file;rank\n")
for row in sorted(rows, key=lambda x: x[0]):
f.write(";".join([str(x) for x in row]) + "\n")
if not self.nocopy:
for r in rows_clean:
shutil.copy(r[0], self.outfolder)
self.parent.destroy()
示例4: init
# 需要導入模塊: import click [as 別名]
# 或者: from click import Path [as 別名]
def init(force, project_name, cloud_vendor, folder) -> int:
"""Initializes an agogosml project by creating a manifest file"""
# Check if exists
folder = Path(folder)
outfile = folder / 'manifest.json'
if outfile.is_file():
if force:
click.echo('Overwriting %s' % outfile)
else:
click.echo('Manifest already exists. Use --force to overwrite')
raise click.Abort()
# Create folder if not exists
outfile.parent.mkdir(parents=True, exist_ok=True)
manifest = build_manifest(project_name, cloud_vendor)
with outfile.open('w') as fobj:
json.dump(manifest, fobj, indent=4)
return 0
示例5: save_workspace
# 需要導入模塊: import click [as 別名]
# 或者: from click import Path [as 別名]
def save_workspace(workspace, numeric, directory, profile, swallow, target):
"""
Save an i3 workspace's layout and running programs to a file.
"""
if workspace is None:
i3 = i3ipc.Connection()
workspace = i3.get_tree().find_focused().workspace().name
if profile is not None:
directory = Path(directory) / 'profiles'
# Create directory if non-existent.
Path(directory).mkdir(parents=True, exist_ok=True)
if target != 'programs_only':
# Save workspace layout to file.
swallow_criteria = swallow.split(',')
layout.save(workspace, numeric, directory, profile, swallow_criteria)
if target != 'layout_only':
# Save running programs to file.
programs.save(workspace, numeric, directory, profile)
示例6: remove
# 需要導入模塊: import click [as 別名]
# 或者: from click import Path [as 別名]
def remove(workspace, directory, profile, target):
"""
Remove saved layout or programs.
"""
if profile is not None:
directory = Path(directory) / 'profiles'
programs_filename = f'{profile}_programs.json'
layout_filename = f'{profile}_layout.json'
elif workspace is not None:
workspace_id = util.filename_filter(workspace)
programs_filename = f'workspace_{workspace_id}_programs.json'
layout_filename = f'workspace_{workspace_id}_layout.json'
else:
util.eprint('Either --profile or --workspace must be specified.')
sys.exit(1)
programs_file = Path(directory) / programs_filename
layout_file = Path(directory) / layout_filename
if target != 'programs_only':
# Delete programs file.
programs_file.unlink()
if target != 'layout_only':
# Delete layout file.
layout_file.unlink()
示例7: migrate_parameters
# 需要導入模塊: import click [as 別名]
# 或者: from click import Path [as 別名]
def migrate_parameters(f):
opts = [
click.option(
'-i', '--in-file',
default=None,
type=click.Path(
exists=True, file_okay=True, dir_okay=False,
readable=True, resolve_path=True),
help='Path to the Quantopian/zipline algorithm file to migrate.'),
click.option(
'-o', '--out-file',
default=None,
type=click.Path(
exists=False, file_okay=True, dir_okay=False,
readable=True, resolve_path=True),
help='Path to the pylivetrader output algorithm file.'),
]
for opt in opts:
f = opt(f)
return f
示例8: xmlfile
# 需要導入模塊: import click [as 別名]
# 或者: from click import Path [as 別名]
def xmlfile(path):
path = Path(path)
try:
if path.suffix == '.gz':
fileobj = gzip.open(path, 'r')
elif path.suffix == '.zck':
import libdnf.utils # we only import if needed
# there is no library yet to read this, we need to unpack on disk
tmppath = tempfile.NamedTemporaryFile(delete=False)
tmppath.close()
libdnf.utils.decompress(str(path), tmppath.name, 0o644, '.zck')
fileobj = open(tmppath.name, 'r')
else:
# uncompressed XML maybe?
fileobj = open(path, 'r')
yield fileobj
finally:
with contextlib.suppress(NameError):
fileobj.close()
with contextlib.suppress(NameError):
tmppath.close()
os.unlink(tmppath.name)
示例9: parquet
# 需要導入模塊: import click [as 別名]
# 或者: from click import Path [as 別名]
def parquet(tables, data_directory, ignore_missing_dependency, **params):
try:
import pyarrow as pa # noqa: F401
import pyarrow.parquet as pq # noqa: F401
except ImportError:
msg = 'PyArrow dependency is missing'
if ignore_missing_dependency:
logger.warning('Ignored: %s', msg)
return 0
else:
raise click.ClickException(msg)
data_directory = Path(data_directory)
for table, df in read_tables(tables, data_directory):
arrow_table = pa.Table.from_pandas(df)
target_path = data_directory / '{}.parquet'.format(table)
pq.write_table(arrow_table, str(target_path))
示例10: clickhouse
# 需要導入模塊: import click [as 別名]
# 或者: from click import Path [as 別名]
def clickhouse(schema, tables, data_directory, **params):
data_directory = Path(data_directory)
logger.info('Initializing ClickHouse...')
engine = init_database('clickhouse+native', params, schema)
for table, df in read_tables(tables, data_directory):
if table == 'batting':
# float nan problem
cols = df.select_dtypes([float]).columns
df[cols] = df[cols].fillna(0).astype(int)
# string None driver problem
cols = df.select_dtypes([object]).columns
df[cols] = df[cols].fillna('')
elif table == 'awards_players':
# string None driver problem
cols = df.select_dtypes([object]).columns
df[cols] = df[cols].fillna('')
insert(engine, table, df)
示例11: profile
# 需要導入模塊: import click [as 別名]
# 或者: from click import Path [as 別名]
def profile(model_specification, results_directory, process):
"""Run a simulation based on the provided MODEL_SPECIFICATION and profile
the run.
"""
model_specification = Path(model_specification)
results_directory = Path(results_directory)
out_stats_file = results_directory / f'{model_specification.name}'.replace('yaml', 'stats')
command = f'run_simulation("{model_specification}")'
cProfile.runctx(command, globals=globals(), locals=locals(), filename=out_stats_file)
if process:
out_txt_file = results_directory / (out_stats_file.name + '.txt')
with out_txt_file.open('w') as f:
p = pstats.Stats(str(out_stats_file), stream=f)
p.sort_stats('cumulative')
p.print_stats()
示例12: multiple_systems_report
# 需要導入模塊: import click [as 別名]
# 或者: from click import Path [as 別名]
def multiple_systems_report(
test_set,
sys_sents_paths,
orig_sents_path=None,
refs_sents_paths=None,
report_path='easse_report.html',
tokenizer='13a',
lowercase=True,
metrics=DEFAULT_METRICS,
system_names=None,
):
"""
Create a HTML report file comparing multiple systems with automatic metrics, plots and samples.
"""
sys_sents_list = [read_lines(path) for path in sys_sents_paths]
orig_sents, refs_sents = get_orig_and_refs_sents(test_set, orig_sents_path, refs_sents_paths)
if system_names is None:
system_names = [Path(path).name for path in sys_sents_paths]
write_multiple_systems_html_report(
report_path, orig_sents, sys_sents_list, refs_sents, system_names=system_names, test_set=test_set,
lowercase=lowercase, tokenizer=tokenizer, metrics=metrics,
)
示例13: edit_inputs
# 需要導入模塊: import click [as 別名]
# 或者: from click import Path [as 別名]
def edit_inputs(client, workflow):
"""Edit workflow inputs."""
for input_ in workflow.inputs:
new_path = click.prompt(
'{0._id}'.format(input_),
default=input_.consumes.path,
)
input_.consumes.path = str(
Path(os.path.abspath(new_path)).relative_to(client.path)
)
for step in workflow.subprocesses:
for argument in step.arguments:
argument.value = click.prompt(
'{0._id}'.format(argument),
default=argument.value,
)
return workflow
示例14: resolve_data_directory
# 需要導入模塊: import click [as 別名]
# 或者: from click import Path [as 別名]
def resolve_data_directory(data_dir, path):
"""Check data directory is within the project path."""
if not data_dir:
return
absolute_data_dir = (Path(path) / data_dir).resolve()
try:
data_dir = absolute_data_dir.relative_to(path)
except ValueError:
raise errors.ParameterError(
f'Data directory {data_dir} is not within project {path}'
)
if str(data_dir).rstrip(os.path.sep) in INVALID_DATA_DIRS:
raise errors.ParameterError(
f'Cannot use {data_dir} as data directory.'
)
return data_dir
示例15: check_arguments
# 需要導入模塊: import click [as 別名]
# 或者: from click import Path [as 別名]
def check_arguments(fortran_library, components, float_type, burnin, timesteps, **kwargs):
fortran_version = check_fortran_library(fortran_library)
if 'fortran' in components or 'fortran-mpi' in components:
if not fortran_library:
raise click.UsageError('Path to fortran library must be given when running fortran components')
if not fortran_version:
raise click.UsageError('Fortran library failed to import')
if fortran_version != 'parallel' and 'fortran-mpi' in components:
raise click.UsageError('Fortran library must be compiled with MPI support for fortran-mpi component')
if float_type != 'float64' and ('fortran' in components or 'fortran-mpi' in components):
raise click.UsageError('Can run Fortran components only with "float64" float type')
if not burnin < timesteps:
raise click.UsageError('burnin must be smaller than number of timesteps')