Intellij Idea 在Java中运行Python脚本返回python退出代码9009(无法使用python)

new9mtju  于 2024-01-06  发布在  Java
关注(0)|答案(1)|浏览(225)

Problem&& what Im doing我写了一个Python脚本,它使用Windows硬件ID检查计算机的端口以搜索特定的读取器,并相应地返回True或False。问题是当我在Java环境中使用BufferedReader和InputStreamReader运行脚本时,Python存在代码9009。

python脚本应该根据连接到计算机的USB读卡器的状态返回true或false值。如上所述,脚本在单独运行时(在IntelliJ,PyCharm和VS Code上)工作。当它试图在我的java程序上运行时,它返回以下内容:

  • Python脚本退出代码:9009*
    我尝试过的事情:

1.检查python解释器/版本/等.|代码运行在我的java IDE(IntelliJ)中
1.在外部运行代码以检查错误|代码在其他任何地方都能正常运行,只是在Java上不行。
1.使用不同版本的文件路径(绝对路径和内容根目录中的路径)|没有工作,下面添加的代码使用绝对路径。

Python脚本

  1. import usbmonitor
  2. from usbmonitor.attributes import ID_MODEL, ID_MODEL_ID, ID_VENDOR_ID
  3. lookFor= "USB\\VID_058F&PID_9540\\5&54725E2&0&2"
  4. def is_connected(lookFor):
  5. # Create the USBMonitor instance
  6. monitor = usbmonitor.USBMonitor()
  7. # Get the current devices
  8. devices_dict = monitor.get_available_devices()
  9. # Check if the device is connected
  10. for device_id, device_info in devices_dict.items():
  11. if device_id.split('\\')[1] == lookFor.split('\\')[1]:
  12. return True
  13. return False
  14. # Look for the specific device
  15. if is_connected("USB\\VID_058F&PID_9540\\5&54725E2&0&2"):
  16. print("Found")
  17. else:
  18. print("Not Found")
  19. if __name__ == "__main__":
  20. print("hello world from python file at: src/java/findUSB.py")
  21. print(is_connected(lookFor))
  22. # Path: src\java\findUSB.py

字符串

Java代码

  1. public boolean usbConnected() {
  2. try {
  3. String pythonScript = "python3"; // Specify the Python interpreter to use (use "python" for Python 2)
  4. String scriptPath = "C:\\CS IA\\src\\java\\findUSB.py"; // Path to the Python script
  5. ProcessBuilder processBuilder = new ProcessBuilder(pythonScript, scriptPath);
  6. Process process = processBuilder.start();
  7. BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
  8. String line = null;
  9. boolean isConnected = false; // Initialize the boolean variable
  10. while ((line = reader.readLine()) != null) {
  11. // Process output of Python script and update the boolean variable
  12. isConnected = Boolean.parseBoolean(line.trim());
  13. }
  14. int exitCode = process.waitFor();
  15. System.out.println("Python script exited with code: " + exitCode);
  16. // Now you can use the 'isConnected' variable to check the result
  17. if (isConnected) {
  18. System.out.println("The device is connected.");
  19. return true;
  20. }
  21. else {
  22. System.out.println("The device is not connected.");
  23. return false;
  24. }
  25. }
  26. catch (IOException | InterruptedException e) {
  27. e.printStackTrace();
  28. return false;
  29. }

可能有用的信息:

os8fio9y

os8fio9y1#

错误代码9009通常与系统无法找到命令或可执行文件的问题相关联。

  • Python不在系统路径中
  • 指定Python脚本的路径不正确

我建议你只使用Java来实现这个功能。使用Java来调用Python并不是一个好主意。

相关问题