首页 > 解决方案 > 在python中通过jpype调用时重定向jar输出

问题描述

我在 python 中使用 jpype 调用 jar 文件中的代码。java代码将一堆输出打印到stdout,我只想重定向到/dev/null。我该怎么做?我无法修改 java 代码(因为它是一个外部项目)。

这是我的python代码:

import jpype
import jpype.imports
jpype.startJVM(jpype.getDefaultJVMPath(), '-Djava.class.path=%s' % astral)
jpype.imports.registerDomain('phylonet')
from phylonet.coalescent import CommandLine
CommandLine.main(['-i', input_file, '-o', output_file])
jpype.shutdownJVM()

幸运的是,我可以将我需要的输出重定向到一个文件,但我仍然会直接将很多不需要的输出直接发送到 stdout。我在进程池中调用多个实例,所以我最终得到来自多个 java 代码实例的乱码输出。

标签: javapythonjpype

解决方案


这里窃取然后翻译成 Python/JPype

import jpype
import jpype.imports
from jpype.types import *

jpype.startJVM(convertStrings=False)

from java.lang import System
from java.io import PrintStream, File

original = System.out
System.out.println("Hello")
System.setOut(PrintStream(File("NUL"))) # NUL for windows, /dev/null for unix
System.out.println("Big")
System.setOut(original)
System.out.println("Boy")

如果您需要对操作系统保持中立,则需要编译自己的 NullPrintStream 概念,因为目前无法在 JPype 中扩展类。


推荐阅读