python-3.xlinuxshellsubprocessenvironment-modules

I'm getting an error "module not found " when I'm trying to execute shell commands through a python script


When the below statement is executed

out1 = subprocess.run("module load python",shell = True, stdout = subprocess.PIPE , stderr = subprocess.STDOUT)

This error is generated.

/bin/sh: module :command not found.

I want to execute shell commands using a python script and this above statement is not working , but when I execute the same statement on the shell then it is working fine and no error is generated.


Solution

  • module is not an external command but a function to define in the shell/script language used. So to enable the module command within a Python script, you need to initialize it with the following code:

    import os
    exec(open('/usr/share/Modules/init/python.py').read())
    

    Replace /usr/share/Modules/init, by the location where the python.py script (from the environment-modules software) is installed on your machine.

    Once initialized, you can call the module function from your script:

    module('load', 'modulefile')