我有一个Java程序,读取一个文件(其中包含来自本地语言的字符),然后填充一个字符串。直接运行程序时,效果很好。
但是当从Python调用同一程序时,则无法填充字符串。
public static void main(String[] args) {
File inputFile = new File("input.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(inputFile),"UTF-8"));
string output = "";
while ((line = br.readLine()) != null) {
// This block never hits when invoked by python. It works fine when java program runs directly.
output +=line+" ";
}
...
}
我从Python调用它的方式如下
cmd = ['java', java_class]
subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
有输入吗?顺便说一句,我正在使用Atom IDE,不确定是否有什么区别。
答案 0 :(得分:1)
我尝试了您的示例,并且对我有用。让我们看看它是否对您有用。然后,我会回复您对这个问题的看法。
import java.io.*;
public class Python2JavaMessaging {
public static void main(String[] args) {
try {
BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));
PrintWriter writer = new PrintWriter("result.txt", "UTF-8");
String s = bufferRead.readLine();
while(s.equals("x")==false) {
writer.println(s);
s = bufferRead.readLine();
}
writer.close();
} catch(IOException e) {
e.printStackTrace();
}
}
}
Python脚本如下:
#!/usr/bin/python
import subprocess
cmd = ['java', '-classpath', '.' , 'Python2JavaMessaging']
p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, encoding='utf8')
p.stdin.write("First line\r\n")
p.stdin.write("Second line\r\n")
p.stdin.write("x\r\n") # this line will not be printed into the file