Advertisement
shinemic

Java - Runtime.exec() example (with consecutive commands)

Sep 25th, 2020
1,742
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.08 KB | None | 0 0
  1. import java.io.*;
  2. import java.nio.charset.Charset;
  3.  
  4. public class RuntimeRunner {
  5.     public static void main(String[] args) throws IOException {
  6.         String conda = "D:\\Miniconda\\condabin\\conda.bat";
  7.         String[] condaEnvs = {
  8.             "PATH=" +
  9.             "D:\\Miniconda\\envs\\py37;" +
  10.             "D:\\Miniconda\\envs\\py37\\Library\\mingw-w64\\bin;" +
  11.             "D:\\Miniconda\\envs\\py37\\Library\\usr\\bin;" +
  12.             "D:\\Miniconda\\envs\\py37\\Library\\bin;" +
  13.             "D:\\Miniconda\\envs\\py37\\Scripts;" +
  14.             "D:\\Miniconda\\envs\\py37\\bin;" +
  15.             "D:\\Miniconda\\condabin;" +
  16.             System.getenv("PATH")
  17.         };
  18.  
  19.         //Runtime.exec
  20.         System.out.println("--- Runtime.exec()");
  21.         System.out.println(">>>>>> single command:");
  22.  
  23.         runtimeTester(conda + " info --envs");
  24.         System.out.print("packages count (base): ");
  25.         runtimeTester(conda + " list | wc -l");
  26.  
  27.         System.out.println("\n>>>>>> consecutive command:");
  28.         System.out.print("packages count (py37): ");
  29.         runtimeTester(conda + " activate py37 && conda list | wc -l");
  30.  
  31.         // Runtime.exec with environment variables
  32.         System.out.println("\n--- Runtime.exec() with environment variables");
  33.         System.out.println(">>>>>> python");
  34.         runtimeWithEnvsTester("cmd /c python -c \"import os;" +
  35.                               "print('\\n'.join([path for path in os.environ['PATH'].split(';')" +
  36.                               "if 'conda' in path]))\"", condaEnvs);
  37.     }
  38.  
  39.     static void runtimeWithEnvsTester(String command, String[] envs) throws IOException {
  40.         Process process = Runtime.getRuntime().exec(command, envs);
  41.         BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream(), Charset.forName("UTF-8")));
  42.         String line;
  43.  
  44.         while ((line = in.readLine()) != null) {
  45.             System.out.println(line);
  46.         }
  47.     }
  48.  
  49.     static void runtimeTester(String command) throws IOException {
  50.         runtimeWithEnvsTester(command, null);
  51.     }
  52. }
  53.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement