Java调用Python程序(命令行调用)(命令行向Python传递参数)
Java中调用Python程序(命令行调用)(命令行向Python传递参数)
实现代码
JavaCallPython.java
import java.io.*;public class JavaCallPython {public static void main(String[] args) {BufferedReader bufferReader = null;try {//创建子进程,调用命令行启动Python程序并传参传递参数Process process = Runtime.getRuntime().exec("python arguments.py Java call Python");//读取Python程序的输出bufferReader = new BufferedReader(new InputStreamReader(process.getInputStream()));String buffer = null;while ((buffer = bufferReader.readLine()) != null) {System.out.println(buffer);}//当前进程等待子进程执行完毕process.waitFor();} catch (InterruptedException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {try {bufferReader.close();} catch (IOException e) {e.printStackTrace();}}}
}
arguments.py
import sys
for arg in sys.argv:print(arg)
输出结果
- 输出命令行传递给Python程序的所有参数
arguments.py
Java
call
Python
最后
- 上述实现需配置Python环境
- 实质上是通过Java调用命令行的方式执行Python程序,同理可以调用C++等程序
- 由于博主水平有限,不免有疏漏之处,欢迎读者随时批评指正,以免造成不必要的误解!
Java调用Python程序(命令行调用)(命令行向Python传递参数)
Java中调用Python程序(命令行调用)(命令行向Python传递参数)
实现代码
JavaCallPython.java
import java.io.*;public class JavaCallPython {public static void main(String[] args) {BufferedReader bufferReader = null;try {//创建子进程,调用命令行启动Python程序并传参传递参数Process process = Runtime.getRuntime().exec("python arguments.py Java call Python");//读取Python程序的输出bufferReader = new BufferedReader(new InputStreamReader(process.getInputStream()));String buffer = null;while ((buffer = bufferReader.readLine()) != null) {System.out.println(buffer);}//当前进程等待子进程执行完毕process.waitFor();} catch (InterruptedException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {try {bufferReader.close();} catch (IOException e) {e.printStackTrace();}}}
}
arguments.py
import sys
for arg in sys.argv:print(arg)
输出结果
- 输出命令行传递给Python程序的所有参数
arguments.py
Java
call
Python
最后
- 上述实现需配置Python环境
- 实质上是通过Java调用命令行的方式执行Python程序,同理可以调用C++等程序
- 由于博主水平有限,不免有疏漏之处,欢迎读者随时批评指正,以免造成不必要的误解!
发布评论