【问题标题】:Java Processbuilder - Catching the exitvalue of another Script?Java Processbuilder - 捕获另一个脚本的退出值?
【发布时间】:2014-05-06 07:03:48
【问题描述】:

我尝试在我的 java 程序中运行 python 脚本。我想要做的是捕获python程序的exitValue并通过System.out.println out编写它。

这是 Python 代码:

import sys
import subprocess
print "hallo"
i = sys.argv[0]
path = "R:\\xxx\\xxx\\xxx\\read"
resultlist = []

if i == 0:
  result = True
else:
  result = False  

resultlist.append(result)
resultlist.append(path)
sys.exit(resultlist)

Processbuilder 方法 .waitFor() 和 .exitValue() 只给出 0 或 1 输出。所以我不能用它。

有没有办法从我的 java 程序中的 python 脚本中捕获 sys.exit(resultlist) 的值/字符串?

【问题讨论】:

  • 呃,当然不是; exit() 的结果是一个整数。你对它的使用一开始就被破坏了
  • 这并不完全正确,在通过 cmd 正常运行脚本时,我得到了应该出现的全文(结果列表)。
  • 那是一个python技巧;但它不值得依赖。

标签: java process processbuilder


【解决方案1】:

man 2 exit:

The function _exit() terminates the calling process "immediately".  Any open file descriptors belonging to the process are closed; any children of the process
are inherited by process 1, init, and the process's parent is sent a SIGCHLD signal.

**The value status is returned to the parent process as the process's exit status, and can be collected using one of the wait(2) family of calls.**

您不能以exit(2)(系统调用)开头返回“复杂值”。如果 python 做到了,那很好,但这是一个“技巧”。不要依赖它。

您要做的是将程序的输出打印到标准输出并捕获标准输出。为此,请使用Process.getInputStream() 并将其吞入,例如ByteArrayOutputStream

由于您使用ProcessBuilder,因此您也可以在执行进程之前使用它的.redirectOutput() 方法。从 Java 7 开始,它有 quite a few options available

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-22
    • 2021-02-15
    • 1970-01-01
    • 1970-01-01
    • 2012-05-16
    • 1970-01-01
    • 2013-08-28
    • 1970-01-01
    相关资源
    最近更新 更多