把调用流程封装为两个类: 第一个类是主执行类,里边提供一个静态方法用于调用Python代码
public class ExecuteCmd {
public static String execute(String[] cmd, String... encoding) {
BufferedReader bReader = null;
InputStreamReader sReader = null;
try {
Process p = Runtime.getRuntime().exec(cmd);
Thread t = new Thread(new InputStreamRunnable(p.getErrorStream(), "ErrorStream"));
t.start();
BufferedInputStream bis = new BufferedInputStream(p.getInputStream());
if (encoding != null && encoding.length != 0) {
sReader = new InputStreamReader(bis, encoding[0]);
} else {
sReader = new InputStreamReader(bis, "utf-8");
}
bReader = new BufferedReader(sReader);
StringBuilder sb = new StringBuilder();
String line;
while ((line = bReader.readLine()) != null) {
sb.append(line);
sb.append("\n");
}
bReader.close();
p.destroy();
return sb.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
第二个类是处理的核心流程,如果执行出错的话,会打印出错误信息
class InputStreamRunnable implements Runnable {
BufferedReader bReader = null;
public InputStreamRunnable(InputStream is, String _type) {
try {
bReader = new BufferedReader(new InputStreamReader(new BufferedInputStream(is), "UTF-8"));
} catch (Exception ex) {
ex.printStackTrace();
}
}
public void run() {
String line;
int num = 0;
try {
while ((line = bReader.readLine()) != null) {
System.out.println("---->"+String.format("%02d",num++)+" "+line);
}
bReader.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
在main方法中直接调用即可
public static void main(String[] args) {
String[] arguments = new String[] { "python", "C:\\Users\\zk\\Desktop\\test\\mytest.py"};
System.out.println(ExecuteCmd.execute(arguments));
}
另外由于是模拟cmd的方式执行,因此Python需要调用的库函数需要显式地添加到环境变量中,不然找不到对应的包,具体为:
import sys
sys.path.append('D:\\anaconda\Lib\site-packages')
还有最后一个点,当前工作路径也要设置一下,不然会找不到当前工程目录下的文件,具体为:
import os
os.chdir('C:\\Users\\zk\\Desktop\\power_test')
相关资源 https://blog.csdn.net/weixin_34198583/article/details/94097452
|