62,616
社区成员
发帖
与我相关
我的任务
分享
Test test=new Test();
Runtime runtime = Runtime.getRuntime();
Process process=null;
try {
process=runtime.exec("java -version");
InputThread in=test.new InputThread(process);
ErrorInputThread error=test.new ErrorInputThread(process);
in.start();
error.start();
try {
OutputStream stream = process.getOutputStream();
stream.write("ipconfig".getBytes());
stream.flush();
stream.close();
int waitFor = process.waitFor();
process.destroy();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Test test=new Test();
// TODO Auto-generated method stub
Runtime runtime = Runtime.getRuntime();
Process process=null;
try {
process=runtime.exec("notepad.exe");
InputThread in=test.new InputThread(process);
ErrorInputThread error=test.new ErrorInputThread(process);
in.start();
error.start();
try {
OutputStream stream = process.getOutputStream();
stream.write("ipconfig".getBytes());
stream.flush();
stream.close();
int waitFor = process.waitFor();
process.destroy();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
import sys
print "begin python script"
# msg = sys.stdin.readline().strip('\n')
msg = raw_input()
print "stdin from java: {}".format(msg)
print 'end python script'
Test.java - 运行a.py,并发送一个信息到a.py的标准输入,最后从a.py的标准输出读取执行结果
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
public class Test {
public static void main(String[] argv) throws Exception {
String command = "python a.py";
Process child = Runtime.getRuntime().exec(command);
OutputStream stdin = child.getOutputStream();
stdin.write("I am Java\n".getBytes());
stdin.flush();
child.waitFor();
System.out.println("begin to get output from python");
String line = null;
BufferedReader reader = new BufferedReader(new InputStreamReader(
child.getInputStream()));
while ((line = reader.readLine()) != null) {
System.out.println("[stdout] " + line);
}
reader.close();
stdin.close();
}
}
结果:
begin to get output
[Stdout] begin python script
[Stdout] stdin from java: I am Java
[Stdout] end python script