Runing Python script in Java return python exit code 9009 (Couldn't lunch python)

270 views Asked by At

Problem&& what Im doing I have written a Python script that checks the ports of the computer in search for a specific reader using it's Windows hardware ID and returns True or False accordingly. problem is when I run the script in my Java environment using BufferedReader and InputStreamReader the python exists with code 9009.

The python script was supposed to return a true or false value according to the state of the USB card reader connected to the computer. As mentioned the script works when its being run alone (both on IntelliJ, PyCharm and VS Code). When it tries to run on my java program it returns the following:

Python script exited with code: 9009

Things I've tried:

  1. checking the python interpreter/ version/ etc... | The code runs within my java IDE (IntelliJ)
  2. Runing the code outside to check for errors | code runs fine everywhere else, just not on java.
  3. Using different versions of the file path (both absolute and within the content root) | didn't work, the code added below uses absolute path.

Python script

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 Code

          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;
        }

information that might be useful:

Absolute path of script: C:\CS IA\src\java\findUSB.py Root path: src/java/findUSB.py python version: Python 3.11.4 Code Files: https://drive.google.com/drive/folders/1wl5pSE24Bt6ToKm0Q-tNP-2F_05wlWPi?usp=sharing

Quick note: I know there's a simple way of doing this check using the dedicated java terminal package however I want to improve my python skills and therefore choose to use python

1

There are 1 answers

0
hibiki On

The error code 9009 is typically associated with an issue where the system cannot find the command or executable file.

  • Python not in the system path
  • Incorrect path to the specified Python script

I recommend that you implement this functionality using Java only. Using Java to call Python is not a good idea.