参考:https://blog.csdn.net/IT_xiao_bai/article/details/79074988
用java调用py脚本
java代码
package luogu;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Luogu {
public static void main(String[] args) {
try {
System.out.println("start");
//下面一行,前面的是调用环境中的python(注意不要用默认的,给个地址),后面的是要运行的python代码,我这里是1.py
String[] args1=new String[]{"C:\\Users\\wyt.DESKTOP-SUI0MPS\\Anaconda3\\envs\\tensorflow\\python","D:\\gxq\\my_project\\Java\\luogu\\src\\luogu\\1.py"};
Process pr=Runtime.getRuntime().exec(args1);
BufferedReader in = new BufferedReader(new InputStreamReader(
pr.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
in.close();
pr.waitFor();
System.out.println("end");
} catch (Exception e) {
e.printStackTrace();
}
}
}
1.py
x=1
y=2
fp=open(r'D:\gxq\my_project\Java\luogu\src\luogu\1.txt','a+')
print(str(x+y),file=fp)
注意上面的地址都要加,不然都是在默认的位置
运行效果为在当前目录生成一个1.txt
可以看到运行成功了,但有的朋友可能会问了,怎么在python程序中函数传递参数并执行出结果,下面我就举一例来说明一下。
用java调用python并传递参数
Luogu.java
package luogu;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Luogu {
public static void main(String[] args) {
int a = 18;
int b = 23;
try {
String[] args1 = new String[] {"C:\\Users\\wyt.DESKTOP-SUI0MPS\\Anaconda3\\envs\\tensorflow\\python","D:\\gxq\\my_project\\Java\\luogu\\src\\luogu\\1.py", String.valueOf(a), String.valueOf(b) };
Process proc = Runtime.getRuntime().exec(args1);// 执行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();
}
}
}
1.py
import sys
def func(a,b):
return (a+b)
if __name__ == '__main__':
a = []
for i in range(1, len(sys.argv)):
a.append((int(sys.argv[i])))
print('恭喜您!java调用python代码成功')
print('脚本名为:%s'%(sys.argv[0]))
fp=open(r'D:\gxq\my_project\Java\luogu\src\luogu\1.txt','a+')
for i in range(1, len(sys.argv)):
print('参数:%s'%(sys.argv[i]),file=fp)
print(str(func(a[0],a[1])),file=fp)
效果: