我正在尝试通过Java运行Python脚本,但我只想在Python中运行一次导入行

0x6upsns  于 2023-03-21  发布在  Java
关注(0)|答案(1)|浏览(89)

我试图通过Java运行Python脚本,但我想在Python中只运行一次导入行,因为我在Python脚本中导入TensorFlow和spaCy。导入它们需要时间,所以我不想通过Java反复运行整个脚本。有什么方法可以做到这一点吗?
这是我的Python代码。这只是示例代码,因为我正在处理这个问题

import sys

while True:
    # read input from standard input
    
    input_str = input()

    # process the input
    output_str = "Processed input: " + input_str

    # write output to standard output
    print(output_str)
    sys.stdout.flush()

这是我的java代码

import java.io.*;
import java.util.Map;
import java.util.Scanner;
import java.util.stream.Stream;

public class RunPythonScriptInteractive {
    public static void main(String[] args) throws Exception {
        // Start the Python process
        try {
            ProcessBuilder builder = new ProcessBuilder();
            Map env = builder.environment();
            env.put("PATH", env.get("PATH") + ":/home/parth/miniconda3/bin");
            builder.command("/bin/bash", "-c", "python pythontry.py");

            builder.redirectErrorStream(true);
            Process process = builder.start();
            Scanner cin = new Scanner(System.in);
            
            BufferedWriter outputWriter = process.outputWriter();
            BufferedReader reader = process.inputReader();

            for (int i = 0; i < 3; i++) {
                String input = cin.nextLine();
                
                outputWriter.write(input);
                outputWriter.newLine();
                outputWriter.flush();

                Stream<String> lines = reader.lines();

                lines.forEach(System.out::println);
            }
            
            outputWriter.close();
            reader.close();

            process.destroy();
        } catch (Exception e) {
            // TODO: handle exception
            System.out.println(e);
        }
    }
}

我试图通过Java代码向Python脚本给予三次输入,但它不起作用。
我希望如果我从Java代码中给予三次,我会从Python脚本中得到三次输出,如下所示:

hello
Processed input: hello

world
Processed input: world

nice
Processed input: nice
mf98qq94

mf98qq941#

我终于找到了解决方案这里是Python代码

import sys

while True:
    # read input from standard input
    input_str = input()

    # process the input
    output_str = "Processed input: " + input_str

    # write output to standard output
    print(output_str)
    sys.stdout.flush()

在Java中,我们必须创建2个类,一个用于提供输入,另一个用于阅读输出。我们将必须使用多线程,一个线程用于向脚本给予输入,另一个线程用于从脚本读取输出。
这里是Main类,它将为脚本给予输入并返回最终输出。

import java.io.BufferedWriter;
import java.util.Map;
import java.util.Scanner;

public class MainClass {
    
    public static void main(String[] args) {
        Process process = null;
        String output="";
        ThreadClass thread = null;
        try {
            
            ProcessBuilder builder = new ProcessBuilder();
            Map env = builder.environment();
            env.put("PATH", env.get("PATH") + ":/home/parth/miniconda3/bin");
            builder.command("/bin/bash", "-c", "python pythontry.py");
            process = builder.start();
            
            Scanner cin = new Scanner(System.in);
            BufferedWriter outputWriter = process.outputWriter();
            thread = new ThreadClass(process);
            thread.start();
            
            for(int i=0; i<3; i++)
            {
                String input = cin.nextLine();
                outputWriter.write(input);
                outputWriter.newLine();
                outputWriter.flush();
            }
            
        } catch (Exception e) {
            // TODO: handle exception
            System.out.println(e);
        }
        finally {
            process.destroy();
            output = thread.getOutput();
            System.out.println(output);
        }
    }

}

下面是第二个线程类,它将读取Python脚本的输出

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.util.Map;
import java.util.Scanner;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Stream;

public class ThreadClass extends Thread {
    
    Process process;
    String output;
    
    public ThreadClass(Process process) {
        // TODO Auto-generated constructor stub
        this.process = process;
        output="";
    }
    
    public void readOutputFromScript() throws IOException {
        try{
            
            BufferedReader reader = process.inputReader();
            String line;
            
            while(true)
            {
                line = reader.readLine();
                if(line==null || line.equals(""))
                {
                    break;
                }
                output+=line;
                System.out.println(line);
            }
            
        } catch (Exception e) {
            // TODO: handle exception
            System.out.println(e);
        }
        
    }
    
    public void run()
    {
        try {
            readOutputFromScript();
        } catch (Exception e) {
            // TODO: handle exception
            System.out.println(e);
        }
    }
    
    public String getOutput()
    {
        return output;
    }
}

感谢所有帮助我达成这个解决方案的朋友

相关问题