How to read SLURM_ARRAY_TASK_ID from R, Matlab or python program

When launching job arrays in SLURM, how can the environment variable SLURM_ARRAY_TASK_ID be read by an R, Matlab or python program? This would be simpler than passing this in as an argument from the job script.

From R:
param<-Sys.getenv(“SLURM_ARRAY_TASK_ID”)

From Matlab:
param=getenv(‘SLURM_ARRAY_TASK_ID’);

From python:
import os

param = os.getenv(‘SLURM_ARRAY_TASK_ID’)

Remember that these usually return strings and not numbers. So you’ll need to cast them into ints if you want to use them for things like multiprocessing or setting ncores in R.

Yes, the values of the environment variables are returned as strings. To cast them to numeric values:

# Python
import os
id = int(os.getenv('SLURM_ARRAY_TASK_ID'))


# R
id <- as.integer(Sys.getenv("SLURM_ARRAY_TASK_ID"))


% MATLAB
id = str2num(getenv('SLURM_ARRAY_TASK_ID'));

An alternative in python would be to insert the following line in your submission script:

python program.py $SLURM_ARRAY_TASK_ID

and in program.py

import sys
sys.argv[1]