This link: Understanding Java Process and Java ProcessBuilder has a sentence saying that Process created by the exec method doesn't own a console.
If I'm calling a python script from the java, where does the Process pickup the environmental variables from?
How can I manipulate/add/remove environmental variables which are used by Java Process class?
You can use the ProcessBuilder.environment()
method to get a Map
of the environment variables.
ProcessBuilder
docs state that:
Returns a string map view of this process builder's environment. Whenever a process builder is created, the environment is initialized to a copy of the current process environment (see System.getenv()). Subprocesses subsequently started by this object's start() method will use this map as their environment.
Using the returned map you can set your own custon env variables which will be used by the process you started.
The sample snippet below, demonstrates the setting of env variables using ProcessBuilder
API:
public static void main(String[] args) throws Exception {
ProcessBuilder pb =
new ProcessBuilder("cmd.exe", "/C", "echo", "%JAVA_HOME%");
Map<String, String> env = pb.environment();
env.put("JAVA_HOME", "c/User/Programs/JDK...");
Process p = pb.start();
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while((line=br.readLine()) != null){
System.out.println(line);
}
try {
int exitValue = p.waitFor();
System.out.println("\n\nExit Value is " + exitValue);
} catch (InterruptedException e) {
e.printStackTrace();
}
}