java Runtime.exec 调用 python 及 python 中线程未运行

0 投票
1 回答
1209 浏览
提问于 2025-04-17 16:45

这是一个关于Python脚本的内容:

import os
import subprocess
import threading
import sys
command= sys.argv[1:]
command=" ".join(command)


def readValue():
    print 'start receive command'
    while True:
        msg=raw_input()
        print 'msg received: %s' % msg
        if 'kill'==msg:
            os.killpg(os.getpgid(p.pid),9)

newThread = threading.Thread(target = readValue, name = "readingThread" )
newThread.setDaemon(1)
newThread.start()

p=subprocess.Popen(command,shell=True,preexec_fn=os.setpgrp)
p.wait()

exitCode=p.poll()
sys.exit(exitCode)

在bash中运行这个脚本

python script.py sleep 100

然后输入一个kill字符串,这样进程就会被成功终止

但是当在Java中运行这个脚本时

Runtime runtime = Runtime.getRuntime();
Process process=runtime.exec("python script.py sleep 100");
Thread.sleep(1000);
process.getOutputStream().write("kill\n".getBytes());
process.waitFor();

Python中的新线程似乎没有运行,线程没有收到kill字符串

有人能告诉我为什么这样不行吗?或者有没有其他方法,比如使用os.setpgrp和os.killpg来终止所有子进程

操作系统:ubuntu 12.04
内核:3.2.0-37-generic
Java版本:1.6.0_34
Python版本:2.7.3

1 个回答

0

试着添加:

process.getOutputStream().flush();

或者,另一种方法:

PrintWriter outputWriter = new PrintWriter(process.getOutputStream(),true);
outputWriter.println("kill");

撰写回答