从Java调用Python代码时出现问题(不使用jython)

从Java调用Python代码时出现问题(不使用jython),java,python,python-3.x,jython,Java,Python,Python 3.x,Jython,我发现这是从java运行(使用exec()方法)python脚本的方法之一。我在python文件中有一个简单的print语句。但是,当我运行程序时,它什么也不做。它既不会打印用python文件编写的语句,也不会引发异常。程序只是终止不执行任何操作: Process p = Runtime.getRuntime().exec("C:\\Python\\Python36-32\\python.exe C:\\test2.py"); 即使这样也不会创建输出文件: Process p = Runtim

我发现这是从java运行(使用exec()方法)python脚本的方法之一。我在python文件中有一个简单的print语句。但是,当我运行程序时,它什么也不做。它既不会打印用python文件编写的语句,也不会引发异常。程序只是终止不执行任何操作:

Process p = Runtime.getRuntime().exec("C:\\Python\\Python36-32\\python.exe C:\\test2.py");
即使这样也不会创建输出文件:

Process p = Runtime.getRuntime().exec("C:\\Python\\Python36-32\\python.exe C:\\test2.py output.txt 2>&1");

有什么问题吗?

我想您可以试试ProcessBuilder类的运气

如果我正确阅读了Oracle文档,默认情况下,std输入和输出将定向到管道,但是ProcessBuilder有一个简单的方法供您显式执行

如果希望Python程序使用与Java程序相同的输出(可能是stdout和stderr),可以像这样使用stg:

ProcessBuilder pb = new ProcessBuilder("C:\\Python\\Python36-32\\python.exe", "C:\\test2.py");
pb.redirectOutput(Redirect.INHERIT);
Process p = pb.start();

启动python进程的一种方法是使用entrypoint-test.cmd

echo Hello
python hello.py
这是hello.py

#!/usr/bin/env python3
import os
if not os.path.exists('dir'):
    os.makedirs('dir')
以下是我的Java代码:

public static void main(String[] args) throws IOException {
    try {
        Process p = Runtime.getRuntime().exec("test.cmd");
        p.waitFor();
        Scanner sc = new Scanner(p.getInputStream());
        while(sc.hasNextLine()){
            System.out.println(sc.nextLine());
        }
        sc.close();
    } catch (Exception err) {
        err.printStackTrace();
    }
}

您可以使用ProcessBuilderAPI,将输出重定向到文件,然后等待结果

public class Main {

    public static final String PYTHON_PATH = "D:\\Anaconda3\\python.exe";
    public static final String PATH_TO_SCRIPT = "D:\\projects\\StartScript\\test.py";

    public static void main(String[] args) throws IOException, InterruptedException {
        ProcessBuilder builder = new ProcessBuilder();
        builder.command(PYTHON_PATH, PATH_TO_SCRIPT);

        // Redirect output to a file
        builder.redirectOutput(new File("output.txt"));

        builder.start().waitFor();

        // Print output to console
        ProcessBuilder.Redirect output = builder.redirectOutput();
        File outputFile = output.file();
        BufferedReader br = new BufferedReader(new FileReader(outputFile));

        String st;
        while ((st = br.readLine()) != null) {
            System.out.println(st);
        }

    }
}

python文件test.py包含一个简单的打印语句:

print("Hello from python")
如果你不需要等待结果,我想这会更简单

public class Main {

    public static final String PYTHON_PATH = "D:\\Anaconda3\\python.exe";
    public static final String PATH_TO_SCRIPT = "D:\\projects\\StartScript\\test.py";

    public static void main(String[] args) throws IOException, InterruptedException {
        ProcessBuilder builder = new ProcessBuilder();
        builder.command(PYTHON_PATH, PATH_TO_SCRIPT);

        // Redirect output to a file
        builder.redirectOutput(new File("output.txt"));

        builder.start().waitFor();

        // Print output to console
        ProcessBuilder.Redirect output = builder.redirectOutput();
        File outputFile = output.file();
        BufferedReader br = new BufferedReader(new FileReader(outputFile));

        String st;
        while ((st = br.readLine()) != null) {
            System.out.println(st);
        }

    }
}

使用流程API也应该有效

就像在您的示例中(我使用上面声明的相同常量):

要查看print语句的输出,需要等待并重定向流。错误流也是如此

现在,如果您像这样破坏python脚本:

print("Hello from python')

您也应该能够看到打印的错误。

如果您使用Windows命令shell程序
cmd.exe
手动键入准确的字符串,它是否达到了预期效果?是的,两条语句都给出了预期结果。我收到此错误:
java.io.IOException:无法运行程序“C:\Python\Python36-32\Python.exe C:\test2.py”:CreateProcess error=2,系统无法在RunninPythonFromJava.main(RunninPythonFromJava.java:16)的java.lang.ProcessBuilder.start(ProcessBuilder.java:1048)处找到指定的文件原因:java.io.IOException:CreateProcess error=2,系统找不到指定的文件
这如何:?这解决了您的问题吗?这就像一个符咒-
ProcessBuilder pb=new ProcessBuilder(“C:\\Python\\Python36-32\\Python.exe”,“C:\\test2.py”);
。更进一步,我如何将参数传递给python并获取返回数据?通过将参数添加到代码中的命令行,您可以像在终端上一样传递参数:
…新的ProcessBuilder(“C:\python\\Python36-32\\python.exe”、“C:\\test2.py”、“arg0”、“arg1”)
或者您想在Java程序和Python程序之间进行某种交互吗?在这种情况下,您可以让Java程序向Python进程的输入流写入一些内容。至于返回数据,我不知道您在做什么。您可以做的一件事是让Java读取Python程序输出的内容穿上衣服,但这对我来说似乎很烦人。