如何解决如何通过通过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
可以立即抑制输出。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。