Skip to content

Commit

Permalink
snakemake-style-guide: Recommend *raw* triple-quoted strings for shel…
Browse files Browse the repository at this point in the history
…l blocks

This greatly enhances the readability of the shell block in Snakemake's
log messages and avoids accidentally interpreting escapes too early.
  • Loading branch information
tsibley committed Aug 20, 2024
1 parent 498cf14 commit 9c81017
Showing 1 changed file with 21 additions and 9 deletions.
30 changes: 21 additions & 9 deletions src/reference/snakemake-style-guide.rst
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ For example, do this:
params:
name = lambda _: config["name"]
shell:
"""
r"""
echo {params.name:q}
"""
Expand Down Expand Up @@ -152,7 +152,7 @@ the ``:q`` modifier for interpolation:
params:
file = "filename with spaces.txt"
shell:
"""
r"""
wc -l {params.file:q}
"""
Expand All @@ -169,31 +169,43 @@ string. Snakemake will interpolate it correctly:
params:
files = ["a.txt", "b.txt", "c.txt"]
shell:
"""
r"""
wc -l {params.files:q}
"""
Use triple-quoted command definitions
=====================================
.. _use-triple-quoted-command-definitions:

Use raw, triple-quoted shell blocks
===================================

Using triple-quoted (``"""`` or ``'''``) command definitions make it
Using raw, triple-quoted (``r"""`` or ``r'''``) ``shell`` blocks makes it
much easier to build readable commands with one-option per line. It also
avoids any nested quoting issues if you need to use literal single or
double quotes in your command.
double quotes in your command. The command will remain readable in
Snakemake's logging messages because it'll look like the source form
(e.g. with backslashes and newlines retained instead of collapsed).

Example:

.. code-block:: python
shell:
"""
r"""
augur parse \
--sequences {input:q} \
--fields {params.fields:q} \
--output-sequences {output.sequences:q} \
--output-metadata {output.metadata:q}
"""
.. hint::
If you're converting interpreted strings to raw strings (e.g.
``"""`` to ``r"""``), make sure to check that they're not relying on
`escape sequences`_ like ``\n``, ``\t``, or ``\\`` to be interpreted by
Python before the shell (Bash) sees them.

.. _escape sequences: https://docs.python.org/3/reference/lexical_analysis.html#escape-sequences

Log standard out and error output to log files and the terminal
===============================================================

Expand All @@ -212,7 +224,7 @@ Example:
log:
"logs/filter.txt"
shell:
"""
r"""
augur filter \
--metadata {input.metadata} \
--output-metadata {output.metadata} 2>&1 | tee {log}
Expand Down

0 comments on commit 9c81017

Please sign in to comment.