Python可执行文件可以告诉您正在运行命令
非交互式的。一旦它意识到它是以非交互方式运行的
将不再尝试与您交互;何必费心打印到
如果没有人在那里的话,那就去stdout或者从stdin读?在
为了证明这是真的,你可以尝试运行例如“ls”或“ps”和
确保它们在你的程序中正常工作,然后运行例如“ftp”或“telnet”
或者“python”,看看它不起作用,什么也不输出。在
用Linux的说法,问题在于我们运行的方式
进程不会将TTY附加到它们。解决办法是欺骗他们
通过创建一个PTY来相信另一端有一个TTY。在
开:我的Mac OS X 10.9.4笔记本电脑,带有CPython 2.7.5和Java 1.8.0_05和
Ubuntu 12.04.4 LTS服务器,带有CPython 2.7.5和Java 1.7.0_55
下面的作品,尽管是以一种非常丑陋的方式:import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
class Foo {
public static void main(String[] args) throws IOException, InterruptedException {
// https://stackoverflow.com/questions/1401002/trick-an-application-into-thinking-its-stdin-is-interactive-not-a-pipe
//
// Using script or unbuffer is the important catch. Without this
// step you cannot use stdin in Python interactively, even with
// python -u. At least script comes with Linux/Mac OS X, but
// unbuffer works fine too.
ProcessBuilder pb;
switch(System.getProperty("os.name")) {
case "Mac OS X":
pb = new ProcessBuilder(
"/usr/bin/script", "-q", "/dev/null", "/usr/bin/python");
break;
default:
// Linux
pb = new ProcessBuilder(
"/usr/bin/script", "-qfc", "/usr/bin/python", "/dev/null");
}
// This doesn't make a difference.
// pb.redirectErrorStream(true);
Process p = pb.start();
char[] readBuffer = new char[1000];
InputStreamReader isr = new InputStreamReader(p.getInputStream());
BufferedReader br = new BufferedReader(isr);
int charCount;
boolean written = false;
while(true) {
if (!br.ready() && !written) {
// Ugly. Should be reading for '>>>' prompt then writing.
Thread.sleep(1000);
if (!written) {
written = true;
OutputStream os = p.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
bw.write("2+2");
bw.newLine();
bw.write("quit()");
bw.newLine();
bw.flush();
bw.close();
}
continue;
}
charCount = br.read(readBuffer);
if (charCount > 0)
System.out.print(new String(readBuffer, 0, charCount));
else
break;
}
}
}
我不会这样做的。相反,我会使用线程来保持交互
避免阻塞读操作,做expect所做的事情,即等待
书写前的某些提示。在上面的代码里,我盲目地睡觉
那就抱着最好的希望吧。在
但是我注意到你使用的是Windows,因为你已经运行了“cmd”。
对不起,我不知道如何在Windows上创建pty。我想是的
你可以在Windows中得到期望;unbuffer是其中的一个实用程序
期望:
或者试试cygwin,但我还是没试过这个。在
有关TTY和PTY的更多背景信息,请参见: