当我尝试通过 python 脚本执行 shell 命令时出现错误 "module not found "

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

当下面语句执行时

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

生成此错误。

/bin/sh: module :command not found.

我想使用 python 脚本执行 shell 命令,上面的语句不起作用,但是当我在 shell 上执行相同的语句时,它工作正常并且没有产生错误。

module不是外部命令,而是用shell/script语言定义的函数。因此,要在 Python 脚本中启用 module 命令,您需要使用以下代码对其进行初始化:

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

/usr/share/Modules/init 替换为 python.py 脚本(来自环境模块软件)在您计算机上的安装位置。

初始化后,您可以从脚本中调用 module 函数:

module('load', 'modulefile')