You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Jython 2.7.2在Java中执行Python脚本遇导入错误求助

解决Jython 2.7.2调用Python脚本时的speech_recognition模块导入错误

问题详情

使用Jython 2.7.2在Java中执行Python脚本时,抛出以下导入错误:

org.python.core.PyException: ImportError: No module named speech_recognition
        at appium.test.pythonReader.record_audio_while_doing_voice_over(pythonReader.java:18)

相关代码

Java代码

import java.io.IOException;

import javax.script.ScriptException;
import org.apache.commons.exec.ExecuteException;
import org.python.util.PythonInterpreter;
import org.testng.annotations.Test;

public class pythonReader {

    @Test
    public void record_audio_while_doing_voice_over()
            throws InterruptedException, ScriptException, ExecuteException, IOException {

        PythonInterpreter python = new PythonInterpreter();
        python.execfile("C:\\SpeechtoText\\audio_transcriber.py");
    }

}

Python代码(audio_transcriber.py)

import speech_recognition as sr

filename = "C:\\SpeechToText\\16-122828-0002.wav"

# initialize the recognizer
r = sr.Recognizer()
with sr.AudioFile(filename) as source:
        # listen for the data (load audio to memory)
        audio_data = r.record(source)
try:
            # recognize (convert from speech to text)
            text = r.recognize_google(audio_data)
            print(text)
except sr.UnknownValueError:
        print("Google Speech Recognition could not understand audio")
except sr.RequestError as e:
        print("Google Speech Recognition error; {0}".format(e))

print("Transaction complete")

解决方案

方案1:手动添加模块路径到Jython的sys.path

Jython默认不会加载CPython的site-packages目录,需要手动指定模块所在路径:

  1. 找到CPython中speech_recognition模块的安装目录(通常在C:\PythonXX\Lib\site-packages,XX为你的Python版本号)
  2. 在Java代码执行脚本前,将该路径添加到Jython的系统路径:
@Test
public void record_audio_while_doing_voice_over()
        throws InterruptedException, ScriptException, ExecuteException, IOException {

    PythonInterpreter python = new PythonInterpreter();
    // 添加CPython的site-packages路径,替换为你的实际路径
    python.exec("import sys");
    python.exec("sys.path.append('C:\\Python39\\Lib\\site-packages')");
    python.execfile("C:\\SpeechtoText\\audio_transcriber.py");
}

也可以通过VM参数提前配置:在Java运行参数中加入-Dpython.path=C:\PythonXX\Lib\site-packages

方案2:直接调用CPython进程执行脚本(推荐)

如果speech_recognition依赖含C扩展的库(Jython不支持C扩展模块),可以绕过Jython,用Java直接调用系统中的Python进程:

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

import org.testng.annotations.Test;

public class pythonReader {

    @Test
    public void record_audio_while_doing_voice_over() throws InterruptedException, IOException {
        // 调用系统python执行脚本,若python不在环境变量需写全路径,如"C:\\Python39\\python.exe"
        ProcessBuilder pb = new ProcessBuilder("python", "C:\\SpeechtoText\\audio_transcriber.py");
        pb.redirectErrorStream(true); // 合并错误输出到标准输出
        Process process = pb.start();

        // 读取脚本输出
        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String line;
        while ((line = reader.readLine()) != null) {
            System.out.println(line);
        }

        // 等待脚本执行完成并获取退出码
        int exitCode = process.waitFor();
        System.out.println("脚本执行完成,退出码:" + exitCode);
    }

}

方案3:复制模块到Jython的site-packages

找到Jython安装目录下的Lib\site-packages文件夹,将CPython中的speech_recognition模块文件夹复制到此处,Jython即可直接识别该模块。

内容的提问来源于stack exchange,提问作者Raja

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 03:54:11