从 Java 代码调用 Python 文件并获取结果时出错
Error in calling Python file from Java code and getting the result
我必须使用 python 在 Java 中执行的代码的结果。
我已经下载了 jython 罐子。
我从互联网上获取以下部分代码。
但是 errorreflected 是
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 所在的文件夹。
我必须使用 python 在 Java 中执行的代码的结果。 我已经下载了 jython 罐子。 我从互联网上获取以下部分代码。 但是 errorreflected 是 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 所在的文件夹。