从java程序到python程序的自定义输入

edqdpe6u  于 2021-09-13  发布在  Java
关注(0)|答案(2)|浏览(286)

我正在尝试制作一个运行python程序的成熟java程序。python程序如下所示:

print('Enter two numbers')
a = int(input())
b = int(input())
c = a + b
print(c)

如果我执行此代码,终端将如下所示:

Enter two numbers
5
3
8

现在,当从java执行此代码时,我想要相同的输出。以下是我的java代码:

import java.io.*;
class RunPython {
    public static void main(String[] args) throws IOException {
        String program = "print('Enter two numbers')\na = int(input())\nb = int(input())\nc = a + b\nprint(a)\nprint(b)\nprint(c)";
        FileWriter fileWriter = new FileWriter("testjava.py");
        BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
        bufferedWriter.write(program);
        bufferedWriter.close();
        Process process = Runtime.getRuntime().exec("python testjava.py");
        InputStreamReader inputStreamReader = new InputStreamReader(process.getInputStream());
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(process.getOutputStream());
        InputStreamReader read = new InputStreamReader(System.in);
        BufferedReader in = new BufferedReader(read);
        String output;
        while (process.isAlive()) {
            while (!bufferedReader.ready());
            System.out.println(bufferedReader.ready());
            while (!(output = bufferedReader.readLine()).isEmpty()) {
                System.out.println(output);
            }
            bufferedReader.close();
            if (process.isAlive()) {
                outputStreamWriter.write(in.readLine());
            }
        }
    }
}

但在运行该程序时,仅显示第一行,并获取第一个输入。之后,程序没有响应。我犯了什么错误?解决办法是什么?

jogvjijk

jogvjijk1#

使用过程:

Process p = new ProcessBuilder(
    "python", "myScript.py", "firstargument Custom input to a Python program from a Java program"
).start();

运行时可以添加任意数量的参数。

使用jython(更简单的选项):

//Java code implementing Jython and calling your python_script.py
import org.python.util.PythonInterpreter;
import org.python.core.*;

public class ImportExample {
   public static void main(String [] args) throws PyException
   {
       PythonInterpreter pi = new PythonInterpreter();
       pi.execfile("path_to_script\\main.py");
       pi.exec("Any custom input from this java program in python to be run");
   }
}

它嵌入了jython,可以在这里阅读。
注意:您可能需要使用 python.path 如果要使用已安装的任何软件包。可以通过在已给出的代码上方添加以下代码来完成此操作:

Properties properties = System.getProperties();
properties.put("python.path", ".\\src\\test\\resources");  // example of path to custom modules (you change this to where the custom modules you would want to import are)
PythonInterpreter.initialize(System.getProperties(), properties, new String[0]);

如果需要进行相反的操作,也可以返回值,可以在jython文档中找到

hsvhsicv

hsvhsicv2#

处理另一个进程的输入和输出有点混乱,您可以在这里找到一个很好的答案
因此,将这些答案应用于代码可能是这样的:

import java.io.*;
import java.util.Scanner;

class RunPython {
    public static void main(String[] args) throws IOException {
//        String program = "print('Enter two numbers')\na = int(input())\nprint(a)\nb = int(input())\nprint(b)\nc = a + b\nprint(c)";
        // If you are using Java 15 or newer you can write code blocks
        String program = """
                print('Enter first number')
                a = int(input())
                print(a)
                print('Enter second number')
                b = int(input())
                print(b)
                c = a + b
                print(c)
                """;
        FileWriter fileWriter = new FileWriter("testjava.py");
        BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
        bufferedWriter.write(program);
        bufferedWriter.close();

        Process process =
                new ProcessBuilder("python", "testjava.py")
                        .redirectErrorStream(true)
                        .start();

        Scanner scan = new Scanner(System.in);

        BufferedReader pythonOutput = new BufferedReader(new InputStreamReader(process.getInputStream()));
        BufferedWriter pythonInput = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));

        Thread thread = new Thread(() -> {
            String input;
            while (process.isAlive() && (input = scan.nextLine()) != null) {
                try {
                    pythonInput.write(input);
                    pythonInput.newLine();
                    pythonInput.flush();
                } catch (IOException e) {
                    System.out.println(e.getLocalizedMessage());
                    process.destroy();
                    System.out.println("Python program terminated.");
                }
            }
        });
        thread.start();

        String output;
        while (process.isAlive() && (output = pythonOutput.readLine()) != null) {
            System.out.println(output);
        }
        pythonOutput.close();
        pythonInput.close();
    }
}

注意,pythoninput在java中是一个bufferedwriter,反之亦然,pythonoutput是一个bufferedreader。

相关问题