Running Python Script using Java with venv
I am trying to run a python script from inside Java, I cant use Jython since I'm using the module Pandas in my script
Here is the code
public class CalculateWarranty { private Logger logger = ApplicationLogger.createLogger(CalculateWarranty.class); public void calculate(String filename) { try { String userHome = System.getProperty("user.home"); ClassLoader classLoader = getClass().getClassLoader(); String projectPath = Paths.get(userHome, "OneDrive", "Documents", "coding projects", "MediaMarkt", "WarrantyReaderWebApplication", "WarrantyReaderApp").toString(); String venvPath = "C:\\Users\\sanso\\OneDrive\\Documents\\codingprojects\\MediaMarkt\\WarrantyReaderWebApplication\\WarrantyReaderApp\\venv\\Scripts\\activate"; String scriptPath = "C:\\Users\\sanso\\OneDrive\\Documents\\codingprojects\\MediaMarkt\\WarrantyReaderWebApplication\\WarrantyReaderApp\\scripts\\calcuscript.py"; String dataPath = "C:\\Users\\sanso\\OneDrive\\Documents\\codingprojects\\MediaMarkt\\WarrantyReaderWebApplication\\WarrantyReaderApp\\src\\main\\resources\\data\\data.xls"; String command = scriptPath + " " + dataPath; logger.error(command); logger.error(venvPath); logger.error(scriptPath); logger.error(dataPath); ProcessBuilder processBuilder = new ProcessBuilder("cmd.exe",venvPath); Process process = processBuilder.start(); InputStream inputStream = process.getInputStream(); InputStreamReader inputStreamReader = new InputStreamReader(inputStream); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); int character; while ((character = bufferedReader.read()) != -1) { System.out.print((char) character); } int exitCode = process.waitFor(); if (exitCode != 0) { System.err.println("The Python script exited with an error."); } } catch (IOException | InterruptedException e) { e.printStackTrace(); } } }
For some reason when I run the method the output gets stuck
Microsoft Windows [Version 10.0.22621.2428] (c) Microsoft Corporation. All rights reserved. C:\Users\sanso\OneDrive\Documents\codingprojects\MediaMarkt\WarrantyReaderWebApplication\WarrantyReaderApp>
It does nothing after this. I have no clue why, I ran the command in a cmd.exe and it worked perfectly fine I also want to know if there is a better approach for this than using a ProcessBuilder And also how can I improve my code so I can deploy this onto a Linux running, I know I would need to modify my hard-coded variables but everytime I used Paths, to get my absolute path I had errors
I tried using Jython Realized that doesn't work, and honestly I kept messing around with the paths, I tried changing how I output the results nothing changed, my code gets blocked, I used Intelijj debug and saw that my while loop gets stuck.
This title and content for this question was made by "NoOne" at this link: https://stackoverflow.com/questions/77385875/running-python-script-using-java-with-venv. Contributions on stackoverflow.com are made under this license.