gpt4 book ai didi

java - 从Java代码调用Python文件并获取结果时出错

转载 作者:行者123 更新时间:2023-12-02 12:02:07 25 4
gpt4 key购买 nike

我必须使用 Java 中 python 执行代码的结果。我已经下载了 jython jar。我从互联网上获取以下部分代码。但是错误反射(reflect)python:无法打开文件“IBM.py”:[Errno 2]没有这样的文件或目录它在哪里搜索文件?我的文件是在 pycharm 项目中创建的。

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class CallPython {

/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
String s = null;
// TODO Auto-generated method stub
Process p = Runtime.getRuntime().exec("python IBM.py");
System.out.println("ayush");
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(p.getInputStream()));

BufferedReader stdError = new BufferedReader(new
InputStreamReader(p.getErrorStream()));

// read the output from the command
System.out.println("Here is the standard output of the command:\n");
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}

// read any errors from the attempted command
System.out.println("Here is the standard error of the command (if any):\n");
while ((s = stdError.readLine()) != null) {
System.out.println(s);
}
}}

最佳答案

您的 IBM.py 文件位于 pycharm 项目文件夹中,并且 java 代码在 java 代码所在的项目文件夹中查找 IBM.py 文件,因此这就是它给出错误的原因。

如果您在任何 IDE 中创建了 Java 项目,然后复制文件 IBM.py 并将其粘贴到 java 项目文件夹中,然后运行此代码,它将正确执行。 :)

如果您只有 CallPython.java 文件,并且没有在任何 IDE 上的 Java 项目中创建它,则将 IBM.py 粘贴到 CallPython.java 所在的同一文件夹中。

关于java - 从Java代码调用Python文件并获取结果时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47172634/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com