java - 使用 Java 检索 python 脚本的输出

标签 java python

我想使用 Java 运行一个基于语音识别的 Python 脚本,并使用 Java 检索脚本输出。

我毫不费力地调用了脚本并运行它。它工作完美。但是我不明白为什么我无法使用 java 恢复输出 print

这是脚本python:

import aiml
import os
import time, sys
import pyttsx
import warnings

# Initialisation of the different mode
# If no specification, Jarvis will run as a text Personnal
mode = "text"
if len(sys.argv) > 1:
    if sys.argv[1] == "--voice" or sys.argv[1] == "voice":
        import speech_recognition as sr
        mode = "voice"

# Jarvis speaking part
def offline_speak(jarvis_speech):
    engine = pyttsx.init()
    engine.say(jarvis_speech)
    engine.runAndWait()

# Jarvis listenning part
def listen():
    # Jarvis listen the environnemnt to capture the voice
    r = sr.Recognizer()
    with sr.Microphone() as source:
        print("Talk to JARVIS: ")
        # Jarvis is listenning
        audio = r.listen(source)
    try:
        # Print and return what Jarvis heard
        print ("test")
        print r.recognize_google(audio, language='fr-FR')
        return r.recognize_google(audio, language='fr-FR')
    except sr.UnknownValueError:
        # If Jarvis doesn't know the sentence or the word you said
        offline_speak("Je n'ai pas compris ce que vous avez dit, pouvez vous repeter s'il vous plait ?")
        print ("test")
        # Return what he heard
        return(listen())
    except sr.RequestError as e:
        # Jarvis didn't understand what you said
        print("Could not request results from Speech Recognition service; {0}".format(e))


# Jarvis running part
while True:
    if mode == "voice":
        response = listen()
        print ("test")
    else:
        response = raw_input("Talk to JARVIS : ")

    offline_speak(response)
    print ("test")

这是我的java类:

import java.io.File;
import java.util.LinkedList;
import java.util.List;

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class PythonCaller {

    private final String pythonPrjPath;
    private final String scriptName;
    private final String args;


    public PythonCaller(String scriptName, String args) {
        this.scriptName = scriptName;
        this.pythonPrjPath = argTreatment();
        this.args = args;
    }


    public void call() throws Exception {
        try {

            List<String> commands = new LinkedList<>();
            commands.add("python");
            commands.add(pythonPrjPath);
            commands.add(args);

            ProcessBuilder pb = new ProcessBuilder(commands);
            Process p = pb.start();

            BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));

            // read the output from the command
            String s;
            while ((s = stdInput.readLine()) != null) {
                System.out.println(s);
            }

        } catch (Exception e) {
            throw e;
        }
    }


    private String argTreatment() {
        ClassLoader classLoader = getClass().getClassLoader();
        File file = new File(classLoader.getResource(scriptName).getFile());
        StringBuilder resPpythonPrjPath = new StringBuilder(file.getAbsolutePath());
        StringBuilder sb = new StringBuilder(resPpythonPrjPath.subSequence(0,90));
        return sb.toString();
    }



    public static void main(String[] args) {

        String tabArgs = "voice";
        PythonCaller pc = new PythonCaller("listener.py", tabArgs);
        try {
            pc.call();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

感谢您的帮助

最佳答案

我无法解决我的问题,所以我决定避免它。我没有读取 print,而是将要检索的数据写入文本文件,然后从 java

读取文本文件

关于java - 使用 Java 检索 python 脚本的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50234927/

相关文章:

java - 使用映射到一个表的实体

python - 如何使用 python-libtorrent 获取 torrent 的对等列表?

Python:如何同时发送多个http请求? (像 fork )

java - 关于取模运算符的使用

java - 新补丁后 Android Studio 无法启动

java - 通过接口(interface)注入(inject)服务类?

python - pyapns - hexlified_token_str

python - 需要帮助在 Python 中返回具有多个变量的字符串

python - pd.get_dummies 数据帧在 Sparse = True 时与 Sparse = False 时大小相同

java - 使用 Java 邮件使用 Gmail SMTP 发送邮件时出现问题