运行 来自 Java 的 CMD
Running CMD from Java
public void run() {
try {
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec("C:\Windows\System32\cmd.exe");
stdin = pr.getOutputStream();
writer = new BufferedWriter(new OutputStreamWriter(stdin));
writer.write("python setup.py py2exe");
writer.close();
BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String line=null;
while((line=input.readLine()) != null) {
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}
}
我正在尝试通过 Java 在命令行中 运行 行 "python setup.py py2exe",但是当我 运行 上面的代码时,它不起作用(有没有错误,但代码应该在目录中创建新文件,但它没有)。
如果我直接将命令 运行 放入命令提示符中,命令将非常完美。
如何通过 Java 实现此 运行?
我建议你使用 ProcessBuilder
that way you can use inheritIO()
之类的东西,
ProcessBuilder pb = new ProcessBuilder("python", "setup.py", "py2exe");
pb.inheritIO();
try {
Process p = pb.start();
p.waitFor(); // <-- wait for the process to finish
} catch (Exception e) {
e.printStackTrace();
}
public void run() {
try {
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec("C:\Windows\System32\cmd.exe");
stdin = pr.getOutputStream();
writer = new BufferedWriter(new OutputStreamWriter(stdin));
writer.write("python setup.py py2exe");
writer.close();
BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String line=null;
while((line=input.readLine()) != null) {
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}
}
我正在尝试通过 Java 在命令行中 运行 行 "python setup.py py2exe",但是当我 运行 上面的代码时,它不起作用(有没有错误,但代码应该在目录中创建新文件,但它没有)。
如果我直接将命令 运行 放入命令提示符中,命令将非常完美。
如何通过 Java 实现此 运行?
我建议你使用 ProcessBuilder
that way you can use inheritIO()
之类的东西,
ProcessBuilder pb = new ProcessBuilder("python", "setup.py", "py2exe");
pb.inheritIO();
try {
Process p = pb.start();
p.waitFor(); // <-- wait for the process to finish
} catch (Exception e) {
e.printStackTrace();
}