Skip to content

utils_templates

customize_template(*, template_name, replacements, script_path)

Customize a bash-script template and write it to disk.

Parameters:

Name Type Description Default
template_filename
required
templates_folder
required
replacements list[tuple[str, str]]
required
Source code in fractal_server/tasks/v2/utils_templates.py
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
def customize_template(
    *,
    template_name: str,
    replacements: list[tuple[str, str]],
    script_path: str,
) -> str:
    """
    Customize a bash-script template and write it to disk.

    Args:
        template_filename:
        templates_folder:
        replacements:
    """
    # Read template
    template_path = TEMPLATES_DIR / template_name
    with template_path.open("r") as f:
        template_data = f.read()
    # Customize template
    script_data = template_data
    for old_new in replacements:
        script_data = script_data.replace(old_new[0], old_new[1])
    # Create parent folder if needed
    Path(script_path).parent.mkdir(exist_ok=True)
    # Write script locally
    with open(script_path, "w") as f:
        f.write(script_data)

parse_script_pip_show_stdout(stdout)

Parse standard output of 4_pip_show.sh

Source code in fractal_server/tasks/v2/utils_templates.py
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
def parse_script_pip_show_stdout(stdout: str) -> dict[str, str]:
    """
    Parse standard output of 4_pip_show.sh
    """
    searches = [
        ("Python interpreter:", "python_bin"),
        ("Package name:", "package_name"),
        ("Package version:", "package_version"),
        ("Package parent folder:", "package_root_parent"),
        ("Manifest absolute path:", "manifest_path"),
    ]
    stdout_lines = stdout.splitlines()
    attributes = dict()
    for search, attribute_name in searches:
        matching_lines = [_line for _line in stdout_lines if search in _line]
        if len(matching_lines) == 0:
            raise ValueError(f"String '{search}' not found in stdout.")
        elif len(matching_lines) > 1:
            raise ValueError(
                f"String '{search}' found too many times "
                f"({len(matching_lines)})."
            )
        else:
            actual_line = matching_lines[0]
            attribute_value = actual_line.split(search)[-1].strip(" ")
            attributes[attribute_name] = attribute_value
    return attributes