通过java运行python文件[重复]

nnvyjq4y  于 2023-01-29  发布在  Java
关注(0)|答案(1)|浏览(130)
    • 此问题在此处已有答案**:

Running python file in cmd through java- %1 is not a valid Win32 application(1个答案)
4个月前关闭。
我正在尝试用java程序执行一个python文件(test1.py)。
下面是我们的代码:

import java.io.*;
import java.nio.charset.StandardCharsets;

public class pro {
    public Process mProcess;

    public pro() {
        Process process;
        try {
            process = Runtime.getRuntime().exec("test1.py");
            mProcess = process;
        } catch (Exception e) {
            System.out.println("Exception Raised" + e.toString());
        }
        InputStream stdout = (mProcess != null) ? mProcess.getInputStream(): null;
        BufferedReader reader = new BufferedReader(new InputStreamReader(stdout, StandardCharsets.UTF_8));
        String line;
        try {
            while ((line = reader.readLine()) != null) {
                System.out.println("stdout: " + line);
            }
        } catch (IOException e) {
            System.out.println("Exception in reading output" + e.toString());
        }
    }
}

线process = Runtime.getRuntime().exec(new String[] { "test1.py"});抛出Exception Raisedjava.io.IOException: Cannot run program "test1.py": CreateProcess error=193, %1 is not a valid Win32 application
怎么啦?

ctehm74n

ctehm74n1#

我觉得唯一的问题是在这条线上

process = Runtime.getRuntime().exec("test1.py");

test1.py 只是一个python文件,您需要像在shell或命令提示符中那样告诉exec如何运行此文件

process = Runtime.getRuntime().exec("python test1.py");

相关问题