最近用到Java向Python传值,找了好多的方法都是直接调用的程序,向python传值的少之又少 要不用了就报错说我缺少什么东西 要不就是没有权限什么的 很苦恼 经过翻阅资料 找到了很多的资料 最后还是解决了
public static void runbat(int jobId) throws IOException, InterruptedException {
//需传入的参数
String a =String.valueOf(jobId);
System.out.println("start;;;" + a);
//设置命令行传入参数
String property1 = System.getProperty("user.dir");
String pythonpath = property1 + "\\config\\winddaydata.py";
String[] args = new String[] { "python", pythonpath, a};
Process pr = Runtime.getRuntime().exec(args);
BufferedReader in = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
// line = decodeUnicode(line);
System.out.println(line); //python打印流
}
in.close();
pr.waitFor();
System.out.println("end");
}
这是在java的代码只需要将python的文件名 还有参数 还有python的地址写入进去即可
下面是python的代码
print ("winddaydata", sys.argv[0])
for i in range(1, len(sys.argv)): //遍历传进的参数
print ("par", i, sys.argv[i])
jobId=sys.argv[i] //传入的参数
最后jobid就是我要传进的参数,这边就可以在后面直接用了
希望可以帮到大家。。。。。也算是一点经验