从Java运行.py文件 [英] Running a .py file from Java

查看:92
本文介绍了从Java运行.py文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从Java代码执行.py文件.我将.py文件移动到我的Java项目的默认目录中,并使用以下代码对其进行调用:

I am trying to execute a .py file from java code. I move the .py file in the default dir of my java project and I call it using the following code:

    String cmd = "python/";
    String py = "file";
    String run = "python  " +cmd+ py + ".py";
    System.out.println(run);
    //Runtime.getRuntime().exec(run);

    Process p = Runtime.getRuntime().exec("python  file.py");

要么使用变量run,要么使用整个路径,要么使用"python file.py"运行我的代码,该消息显示消息构建成功的总时间为0秒,而没有执行file.py.我这是什么问题?

Either using variable run, or the whole path or "python file.py" my code is running showing the message build successful total time 0 seconds without execute the file.py. What is my problem here?

推荐答案

您也可以这样使用:

String command = "python /c start python path\to\script\script.py";
Process p = Runtime.getRuntime().exec(command + param );

String prg = "import sys";
BufferedWriter out = new BufferedWriter(new FileWriter("path/a.py"));
out.write(prg);
out.close();
Process p = Runtime.getRuntime().exec("python path/a.py");
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
String ret = in.readLine();
System.out.println("value is : "+ret);

从Java运行Python脚本

Run Python script from Java

这篇关于从Java运行.py文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆