当前位置: 首页>>代码示例>>Python>>正文


Python click.Path方法代码示例

本文整理汇总了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) 
开发者ID:item4,项目名称:yui,代码行数:24,代码来源:cli.py

示例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.'
            ) 
开发者ID:pgjones,项目名称:quart,代码行数:19,代码来源:cli.py

示例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() 
开发者ID:cwerner,项目名称:fastclass,代码行数:26,代码来源:fc_clean.py

示例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 
开发者ID:microsoft,项目名称:agogosml,代码行数:19,代码来源:init.py

示例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) 
开发者ID:JonnyHaystack,项目名称:i3-resurrect,代码行数:24,代码来源:main.py

示例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() 
开发者ID:JonnyHaystack,项目名称:i3-resurrect,代码行数:27,代码来源:main.py

示例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 
开发者ID:alpacahq,项目名称:pylivetrader,代码行数:22,代码来源:__main__.py

示例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) 
开发者ID:fedora-python,项目名称:portingdb,代码行数:24,代码来源:check_drops.py

示例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)) 
开发者ID:ibis-project,项目名称:ibis,代码行数:19,代码来源:datamgr.py

示例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) 
开发者ID:ibis-project,项目名称:ibis,代码行数:20,代码来源:datamgr.py

示例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() 
开发者ID:ihmeuw,项目名称:vivarium,代码行数:19,代码来源:cli.py

示例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,
            ) 
开发者ID:feralvam,项目名称:easse,代码行数:24,代码来源:cli.py

示例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 
开发者ID:SwissDataScienceCenter,项目名称:renku-python,代码行数:21,代码来源:rerun.py

示例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 
开发者ID:SwissDataScienceCenter,项目名称:renku-python,代码行数:22,代码来源:init.py

示例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') 
开发者ID:team-ocean,项目名称:veros,代码行数:19,代码来源:run_benchmarks.py


注:本文中的click.Path方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。