如何通过通过subprocess.Popen运行的可选输入来使可执行文件静音?

问题描述

我遇到了对通用代数建模系统(GAMS)的gams可执行文件调用的问题,该可执行文件可以作为免费试用版here获得。

在我正在构建的应用程序中,我通过一个函数调用了该可执行文件和其他可执行文件,该函数具有通过重定向dev/null来使输出静音的功能,基本上是:

def syscall(executable,*args,silent=False):
    """Issue a system call.

    Arguments
    ---------
    executable : str
        the name of the executable to be called. Needs to be an executable in
        one of the directories listed in the PATH environment variable.
    args : list of str
        the arguments passed to the executable
    silent : bool
        whether the output should be hidden from stdout (default: False)

    Returns
    -------
    ret : int
        the return code of the system call
    """
    from subprocess import Popen,PIPE,STDOUT
    import sys

    if silent:
        process = Popen([executable,*args],stderr=subprocess.DEVNULL,stdout=subprocess.DEVNULL)
    else:
        process = Popen([executable,stderr=STDOUT,stdout=PIPE)
    process.wait()  # wait until executable has finished
    ret = process.returncode
    return ret

虽然它可以与任何其他可执行文件完美地结合在一起,但是gams只是不想安静,即syscall('gams',silent=True)syscall('gams','Problem.gms',silent=True)仍然提供输出。 在交互式解释器中尝试此操作时,我意识到这似乎是因为gams允许来自stdin的输入!

有什么方法可以预加载标准输入以便输出

解决方法

您实际看到的是哪种输出?您使用的是什么版本的GAMS?默认情况下,较旧的版本而不是stdOut写入控制台(如果可用)。如果您的GAMS版本不是最新版本,则可以通过将参数<UserPosition data={JSON.parse(`{{ data_response }}`)} /> (请参见https://www.gams.com/32/docs/UG_GamsCall.html#GAMSAOlogoption)设置为logOption来更改。或者,也许更好,因为您仍然不希望输出,因此设置3可以立即抑制输出。