I tried to use a shell variable to access Python dictionary values inside the shell commands but got an error. The following is a simplified example in which $x needs to be used:
my_dict = {}
my_dict['SHELL_KEY'] = 'key3'
print(my_dict)
rule another_rule:
output: "output.txt"
shell:
"""
x='SHELL_KEY'
echo {my_dict[$x]} > {output}
"""
RuleException in rule another_rule in file /home/zhujack/workflow/ngs_aPipe_snake_dev/rules/align.rules, line 43:
NameError: The name '$x' is unknown in this context. Please make sure that you defined that variable. Also note that braces not used for variable access have to be escaped by repeating them, i.e. {{print $1}}, when formatting the following:
x='SHELL_KEY'
echo {my_dict[$x]} > {output}
This won't work, because Snakemake does not pass the Python dictionary through to Bash. It just replaces the placeholders in the command with strings. Just as Bash does not know about the my_dict
dictionary, Snakemake does not know about the x
variable, hence the error you see. Depending on what you are really trying to do, here are two suggestions.
my_dict = {}
my_dict['SHELL_KEY'] = 'key3'
print(my_dict)
rule another_rule:
output: "output.txt"
run:
x = 'SHELL_KEY'
shell_val = my_dict[x]
shell("echo {shell_val} > {output}")
or
my_dict = {}
my_dict['SHELL_KEY'] = 'key3'
print(my_dict)
rule another_rule:
output: "output_{key}.txt"
params:
x = lambda wc: my_dict[wc.key]
shell:
"""
echo {params.x} > {output}
"""