Created
April 17, 2020 10:44
-
-
Save MarkZhangTW/b6d93780b422929ac668c3341a693dd5 to your computer and use it in GitHub Desktop.
Run python script in Java in Windows
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class App { | |
public static void main(String[] args) throws IOException { | |
final String result = runPython("script.py", "arg1", "arg2"); | |
System.out.println(result); | |
} | |
private static String runPython(String script, String... args) throws IOException { | |
List<String> newArgs = new ArrayList<>(); | |
newArgs.add(script); | |
newArgs.addAll(Arrays.asList(args)); | |
return runCommand("python", newArgs.toArray(new String[0])).get(0); | |
} | |
private static List<String> runCommand(String exe, String... args) throws IOException { | |
List<String> command = new ArrayList<>(); | |
command.add(exe); | |
command.addAll(Arrays.asList(args)); | |
ProcessBuilder pb = new ProcessBuilder(command); | |
pb.environment().put("PATH", | |
"C:\\ProgramData\\Anaconda3;C:\\ProgramData\\Anaconda3\\Library\\mingw-w64\\bin;C:\\ProgramData\\Anaconda3\\Library\\usr\\bin;C:\\ProgramData\\Anaconda3\\Library\\bin;C:\\ProgramData\\Anaconda3\\Scripts;C:\\ProgramData\\Anaconda3\\bin;" | |
); | |
Process p = pb.start(); | |
InputStream is = p.getInputStream(); | |
BufferedReader reader = new BufferedReader(new InputStreamReader(is)); | |
List<String> output = reader.lines().collect(Collectors.toList()); | |
reader.close(); | |
return output; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment