I have some simple bash scripts that I would like to translate in python. I need to define some bash environment variables before calling the external program with subprocess. In particular I need to load a module environment. The original bash looks something like this
#!/bin/bash
source /etc/profile.d/modules.sh
module purge
module load intel
./my_code
I want to call my_code with subprocess, but how do I pass the variables defined by module to the shell?
Edit:
my first attempt to convert the above script is
#!/usr/bin/python -tt
import subprocess
subprocess.call("source /etc/profile.d/modules.sh",shell=True)
subprocess.call("module purge",shell=True)
subprocess.call("module load intel",shell=True)
subprocess.call("./mycode",shell=True)
but this fails, because the environment variables (that I think are LIBRARY_PATH and PATH and C_INCLUDE) are modified in the shell launched by subprocess, but then this shell dies and these variables are not inherited by subsequent shells. So the question is: how can I launch a modules command and then save the relevant variables with os.environ ?
-
3So what is your question?slider– slider2014年03月19日 14:21:57 +00:00Commented Mar 19, 2014 at 14:21
-
I think now the question is clear, isn't it?simona– simona2014年03月19日 14:32:08 +00:00Commented Mar 19, 2014 at 14:32
2 Answers 2
You could use a multiline string so that the environment is modified in the same shell process:
from subprocess import check_call
check_call("""
source /etc/profile.d/modules.sh
module purge
module load intel
./my_code
""", shell=True, executable="/bin/bash")
4 Comments
import os
os.environ is a dict of environment variables (exported shell variables)