Accessing the path of the `--configfile` within Snakefile

Viewed 261

Using Snakemake, is there any way to access the path of a config file passed to the workflow using the --configfile flag?


From poking around in the source for the workflow object, I initially thought the following minimal Snakefile

print(str(workflow.configfiles))

would print a list containing all config files, but running snakemake --configfile [path/to/config/file] -j 1 simply prints an empty list (Snakemake 6.1.1).

3 Answers

Snakemake is a module of Python, and you may use all functions and variables that you would use in regular Python scripts. For example this code will print the command line arguments that you have specified running the Snakemake script:

import sys

print(sys.argv)

The answer by @MSR has a slight issue when running a workflow on cluster. Apparently, each job (rule) sent to the cluster will also run all the global code, however, it does not have --configfile in its sys.argv, which will result in an error when running the job. Instead, it has --configfiles, so what I had to do was:

if '--configfile' in sys.argv:
    i = sys.argv.index('--configfile')
elif '--configfiles' in sys.argv:
    i = sys.argv.index('--configfiles')
conf_path = sys.argv[i+1]

I don't know if that's the best solution, but it worked for me. Would be nice if snakemake had a more elegant way off accession the config path, like workflow.configfile.

Based on Dmitry Kuzminov's answer, a simple solution for the case when only a single config file is present would be:

import sys

args = sys.argv
config_path = args[args.index("--configfiles") + 1]
print(config_path)
Related