0

我正在尝试在 hpc 环境中运行此脚本,目的是将环境中可用的所有模块写入文本文件。使用的模块系统是 lmod。

该脚本对于我尝试过的任何常规 bash 命令(例如echoor )都按预期工作ls,但是当我尝试使用如下所示的任何模块命令时,我将结果输出到我的终端并且没有写入文本文件。

我曾尝试使用 os 模块,os.popenstream.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)
4

1 回答 1

0

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)

它应该工作(它在我测试的系统上工作)。

于 2022-02-04T16:45:46.420 回答