一、Java内置Jpython库(不推荐)
1.1 下载与使用
可以在官网下载jar包,官网:http://ftp.cuhk.edu.hk/pub/packages/apache.org/
或者使用maven进行jar包下载
1
2
3
4
5
|
< dependency > < groupId >org.python</ groupId > < artifactId >jython-standalone</ artifactId > < version >2.7.0</ version > </ dependency > |
执行代码样例:
1
2
3
|
PythonInterpreter interpreter = new PythonInterpreter(); interpreter.exec( "a=[5,2,3,9,4,0]; " ); interpreter.exec( "print(sorted(a));" ); |
1.2 缺陷
Jython内置的库有限,而且很多库不存在,会报no model的错误,所以这里不推荐大家使用。
二、使用Runtime.getRuntime()执行脚本⽂件
2.1 使用
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; publicclass Demo1 { publicstaticvoid main(String[] args) { Process proc; // 编译器是python String exe = "python" ; // py文件存的绝对路径 String path = "D:\\NLP.py" ; // 传入的参数 String args = "今天过的很开心" ; try { proc = Runtime.getRuntime().exec(exe + ' ' + path + ' ' + args); // 执⾏py⽂件 // ⽤输⼊输出流来截取结果 BufferedReader in = new BufferedReader( new InputStreamReader(proc.getInputStream())); String line = null ; while ((line = in.readLine()) != null ) { System.out.println(line); } in.close(); proc.waitFor(); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } } |
2.2 缺陷
如果在你的python中,会使用自己包中的其他python文件中的函数,那么很有可能无法导入,但是不会报错,只会返回一个null。
三、利用cmd调用python文件
3.1 使用
这个方法就类似于在cmd中,使用 python file.py 参数 直接执行python文件一样
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; publicclass Demo1 { publicstaticvoid main(String[] args) { Process proc; // 编译器是python String exe = "cmd.exe" ; // py文件存的绝对路径 String path = "D:\\NLP.py" ; // 传入的参数 String args = "今天过的很开心" ; try { proc = Runtime.getRuntime().exec(exe + " \c start " + path + ' ' + args); // 执⾏py⽂件 proc.waitFor(); } catch (Exception e) { e.printStackTrace(); } } } |
3.2 优化
考虑到python是否正在进行,或者是否调用python,可设置一些函数用于辅助:
这里没有使用参数,直接对文件进行读取,传参可能会存在编码问题,Java默认UTF-8,cmd是GBK
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
|
package com.Lee.utils; import java.io.*; public class NLPUtils { // NLP处理 public static String NLP(String data) throws Exception{ try { inputToFile(data); } catch (Exception e){ e.printStackTrace(); } System.out.println( "调用python程序" ); Process pcs = null ; String py = "python.exe" ; try { if (processIsRun(py)) killProcess(py); System.out.println( "start" ); pcs = Runtime.getRuntime().exec( "cmd.exe /c start F://python_project//NLP.bat" ); pcs.waitFor(); if (processIsRun(py)){ System.out.println( "正在执行" ); Thread.currentThread().sleep( 30000 ); } System.out.println( "end" ); } catch (Exception e){ e.printStackTrace(); } String result = "" ; try { System.out.println( "out:" + outputFromFile()); result = outputFromFile(); } catch (Exception e){ e.printStackTrace(); } return result; } // 清空文件 public static void clearInfoForFile(String fileName) { File file = new File(fileName); try { if (!file.exists()) { file.createNewFile(); } FileWriter fileWriter = new FileWriter(file); fileWriter.write( "" ); fileWriter.flush(); fileWriter.close(); } catch (Exception e) { e.printStackTrace(); } } // 输入文件,参数为输出字符串 public static void inputToFile(String input) throws Exception{ // 写入前清空 clearInfoForFile( "F:\\python_project\\input.txt" ); //创建写入流 FileWriter writer= new FileWriter( "F:\\python_project\\input.txt" ); // 写入 writer.write(input + "\r\n" ); //关闭资源 writer.flush(); writer.close(); } // 读取文件 public static String outputFromFile() throws Exception{ InputStreamReader isr = new InputStreamReader( new FileInputStream( "F:\\python_project\\output.txt" ), "GBK" ); BufferedReader read = new BufferedReader(isr); String s = null ; String result = "" ; while ((s = read.readLine()) != null ) result += s; isr.close(); read.close(); return result; } // 杀掉一个进程 public static void killProcess(String name) { try { String[] cmd = { "tasklist" }; Process proc = Runtime.getRuntime().exec(cmd); BufferedReader in = new BufferedReader( new InputStreamReader(proc.getInputStream())); String string_Temp = in.readLine(); while (string_Temp != null ) { // System.out.println(string_Temp); if (string_Temp.indexOf(name) != - 1 ) { Runtime.getRuntime().exec( "taskkill /F /IM " + name); System.out.println( "杀死进程 " + name); } string_Temp = in.readLine(); } } catch (Exception e) { e.printStackTrace(); } } // 判断进程是否存在 public static boolean processIsRun(String ProjectName) { boolean flag = false ; try { Process p = Runtime.getRuntime().exec( "cmd /c tasklist " ); ByteArrayOutputStream baos = new ByteArrayOutputStream(); InputStream os = p.getInputStream(); byte b[] = new byte [ 256 ]; while (os.read(b) > 0 ) baos.write(b); String s = baos.toString(); if (s.indexOf(ProjectName) >= 0 ) { flag = true ; } else { flag = false ; } } catch (Exception e) { e.printStackTrace(); } return flag; } } |
总结
到此这篇关于如何在Java中调用python文件执行的文章就介绍到这了,更多相关Java调用python文件执行内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!
原文链接:https://blog.csdn.net/qq_44027696/article/details/124570334