-
Notifications
You must be signed in to change notification settings - Fork 2
Executing Python code
So far, all examples of rules we presented were using the shell directive introduced in the Defining rules section to run a shell command. Instead of a shell command, it is possible to run Python code using the run directive. In the code snippet, variables and directives from the rule can be accessed just like in the shell directive.
Let us recall the last example rule implemented in the Parameters section:
rule first_step:
input:
'data/first_step.tsv'
output:
'results/first_step.txt'
params:
lines = 5
shell:
'head -n {params.lines} {input} > {output}'Although it would not be very useful in this case, we could replace the shell command with Python code:
rule first_step:
input:
'data/first_step.tsv'
output:
'results/first_step.txt'
params:
lines = 5
run:
input_file = open(input[0])
output_file = open(output[0], ‘w’)
for i in range(params.lines):
output_file.write(input_file.readline())Snakemake has a built-in function to submit a shell command from a run block, which takes a string as input and returns the output of the command:
shell('command {input} {output} {params}')The run directive can be useful to design wrappers around shell commands or implement small functions for which there is no simple existing software. However, for functions involving complex Python code, the script approach is preferred.
- Defining rules
- Rule dependencies
- Wildcards
- Executing workflows
- The expand syntax
- Non-file rule parameters
- Executing Python code