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

Java调用Python脚本返回退出码9009问题排查求助

问题:Java调用Python读卡器检测脚本返回退出码9009

我编写了一个Python脚本,通过Windows硬件ID检测计算机端口中是否存在特定读卡器,最终返回True或False。该脚本在IntelliJ、PyCharm、VS Code中单独运行均正常,但通过Java的BufferedReader和InputStreamReader调用时,Python返回退出码9009。

已尝试的操作

  • 检查Python解释器、版本等信息,脚本可在Java IDE(IntelliJ)内正常运行
  • 在外部环境直接运行脚本无任何报错
  • 分别使用绝对路径和项目根路径指定脚本路径,均无效(当前代码已使用绝对路径)

相关代码

Python脚本(路径:C:\CS IA\src\java\findUSB.py,Python版本3.11.4)

import usbmonitor
from usbmonitor.attributes import ID_MODEL, ID_MODEL_ID, ID_VENDOR_ID


lookFor= "USB\\VID_058F&PID_9540\\5&54725E2&0&2"
def is_connected(lookFor):
    # Create the USBMonitor instance
    monitor = usbmonitor.USBMonitor()

    # Get the current devices
    devices_dict = monitor.get_available_devices()

    # Check if the device is connected
    for device_id, device_info in devices_dict.items():
        if device_id.split('\\')[1] == lookFor.split('\\')[1]:
            return True

    return False


# Look for the specific device
if is_connected("USB\\VID_058F&PID_9540\\5&54725E2&0&2"):
    print("Found")
else:
    print("Not Found")


if __name__ == "__main__":
    print("hello world from python file at: src/java/findUSB.py")
    print(is_connected(lookFor))

# Path: src\java\findUSB.py

Java代码

public boolean usbConnected() {

    try {
        String pythonScript = "python3";  // Specify the Python interpreter to use (use "python" for Python 2)
        String scriptPath = "C:\\CS IA\\src\\java\\findUSB.py";  // Path to the Python script
        ProcessBuilder processBuilder = new ProcessBuilder(pythonScript, scriptPath);
        Process process = processBuilder.start();
        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String line = null;


        boolean isConnected = false;  // Initialize the boolean variable

        while ((line = reader.readLine()) != null) {
            // Process output of Python script and update the boolean variable
            isConnected = Boolean.parseBoolean(line.trim());
        }

        int exitCode = process.waitFor();
        System.out.println("Python script exited with code: " + exitCode);

        // Now you can use the 'isConnected' variable to check the result
        if (isConnected) {
            System.out.println("The device is connected.");
            return true;
        } 
        else {
            System.out.println("The device is not connected.");
            return false;
        }
    } 
    catch (IOException | InterruptedException e) {
        e.printStackTrace();
        return false;
    }
}

补充说明

我知晓可通过Java专用包实现检测,但为提升Python技能选择此方案。

内容的提问来源于stack exchange,提问作者Shaked Ben Eliezer

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 10:43:15