无法在 hpc 环境中使用 python 将 lmod 命令输出到文本文件
Can't output lmod commands to text file using python in hpc environment
我正尝试在 h.p.c 环境中 运行 此脚本,目的是将环境中可用的所有模块写入文本文件。使用的模块系统是 lmod.
对于我尝试过的任何常规 bash 命令,如 echo
或 ls
,此脚本按预期工作,但是当我尝试使用任何模块命令时,如下所示,我将结果输出到我的终端,没有任何内容写入文本文件。
我曾尝试将 os 模块与 os.popen
和 stream.read()
一起使用,但我遇到了同样的问题。
#!/usr/bin/python
import subprocess
def shell_cmd(command):
"""Executes the given command within terminal and returns the output as a string
:param command: the command that will be executed in the shell
:type command: str
:return: the output of the command
:rtype: str
"""
process = subprocess.run([command], stdout=subprocess.PIPE, shell=True, universal_newlines=True)
return process
#runs command
cmd = 'module avail'
out = shell_cmd(cmd)
output = out.stdout
# write output to text file
with open('output.txt', 'w+') as file:
file.write(output)
Lmod(和环境模块)将它们的输出发送到 STDERR,而不是 STDOUT,所以我认为您应该将脚本修改为:
#!/usr/bin/env python
import subprocess
def shell_cmd(command):
"""Executes the given command within terminal and returns the output as a string
:param command: the command that will be executed in the shell
:type command: str
:return: the output of the command
:rtype: str
"""
process = subprocess.run([command], stderr=subprocess.PIPE, shell=True, universal_newlines=True)
return process
#runs command
cmd = 'module avail'
out = shell_cmd(cmd)
output = out.stderr
# write output to text file
with open('output.txt', 'w+') as file:
file.write(output)
它应该可以工作(它在我测试的系统上工作)。
我正尝试在 h.p.c 环境中 运行 此脚本,目的是将环境中可用的所有模块写入文本文件。使用的模块系统是 lmod.
对于我尝试过的任何常规 bash 命令,如 echo
或 ls
,此脚本按预期工作,但是当我尝试使用任何模块命令时,如下所示,我将结果输出到我的终端,没有任何内容写入文本文件。
我曾尝试将 os 模块与 os.popen
和 stream.read()
一起使用,但我遇到了同样的问题。
#!/usr/bin/python
import subprocess
def shell_cmd(command):
"""Executes the given command within terminal and returns the output as a string
:param command: the command that will be executed in the shell
:type command: str
:return: the output of the command
:rtype: str
"""
process = subprocess.run([command], stdout=subprocess.PIPE, shell=True, universal_newlines=True)
return process
#runs command
cmd = 'module avail'
out = shell_cmd(cmd)
output = out.stdout
# write output to text file
with open('output.txt', 'w+') as file:
file.write(output)
Lmod(和环境模块)将它们的输出发送到 STDERR,而不是 STDOUT,所以我认为您应该将脚本修改为:
#!/usr/bin/env python
import subprocess
def shell_cmd(command):
"""Executes the given command within terminal and returns the output as a string
:param command: the command that will be executed in the shell
:type command: str
:return: the output of the command
:rtype: str
"""
process = subprocess.run([command], stderr=subprocess.PIPE, shell=True, universal_newlines=True)
return process
#runs command
cmd = 'module avail'
out = shell_cmd(cmd)
output = out.stderr
# write output to text file
with open('output.txt', 'w+') as file:
file.write(output)
它应该可以工作(它在我测试的系统上工作)。