ProcessBuilder 或 Runtime 类 从哪里获取环境变量?
Where does ProcessBuilder or Runtime classes get the environment variables from?
这个link:Understanding Java Process and Java ProcessBuilder有一句话说用exec方法创建的进程不拥有控制台
如果我从 java 调用 python 脚本,进程从哪里获取环境变量?
如何 manipulate/add/remove Java 进程 class 使用的环境变量?
您可以使用ProcessBuilder.environment()
方法获取Map
的环境变量。
ProcessBuilder
文档指出:
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.
使用返回的映射,您可以设置您自己的自定义环境变量,您启动的进程将使用这些变量。
下面的示例片段演示了使用 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();
}
}
这个link:Understanding Java Process and Java ProcessBuilder有一句话说用exec方法创建的进程不拥有控制台
如果我从 java 调用 python 脚本,进程从哪里获取环境变量?
如何 manipulate/add/remove Java 进程 class 使用的环境变量?
您可以使用ProcessBuilder.environment()
方法获取Map
的环境变量。
ProcessBuilder
文档指出:
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.
使用返回的映射,您可以设置您自己的自定义环境变量,您启动的进程将使用这些变量。
下面的示例片段演示了使用 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();
}
}