1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
|
# -*- python -*-
from __future__ import print_function
from subprocess import PIPE, Popen
import os, sys
def module(command, *arguments, **kwargs):
"""
Execute a regular Lmod command and apply environment changes to
the current Python environment (i.e. os.environ).
In case len(arguments) == 1 the string will be split on whitespace into
separate arguments. Pass a list of strings to avoid this.
Raises an exception in case Lmod execution returned a non-zero
exit code.
Use with keyword argument show_environ_updates=True to show the actual
changes made to os.environ (mostly for debugging).
Examples:
module('list')
module('load', 'gcc')
module('load', 'gcc cmake')
module('load', 'gcc cmake', show_environ_updates=True)
"""
numArgs = len(arguments)
A = ['@PKG@/libexec/lmod', 'python', command]
if (numArgs == 1):
A += arguments[0].split()
else:
A += list(arguments)
proc = Popen(A, stdout=PIPE, stderr=PIPE)
status = proc.returncode
stdout, stderr = proc.communicate()
err_out = sys.stderr
if (os.environ.get('LMOD_REDIRECT','@redirect@') != 'no'):
err_out=sys.stdout
print(stderr.decode(),file=err_out)
if ('show_environ_updates' in kwargs):
print(stdout.decode())
exec(stdout.decode())
return status, stderr.decode()
|