从Java运行.py文件
我试图从java代码执行.py文件。 我将.py文件移动到我的java项目的默认目录中,并使用以下代码调用它:
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");
无论是使用变量运行,还是整个路径或“python file.py”,我的代码都在运行,显示消息构建成功总时间0秒而不执行file.py. 我的问题在这里是什么?
你也可以这样使用:
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脚本
我相信我们可以使用ProcessBuilder
Runtime.getRuntime().exec("python "+cmd + py + ".py"); ..... since exec has its own process we can use that ProcessBuilder builder = new ProcessBuilder("python", py + ".py"); builder.directory(new File(cmd)); builder.redirectError(); .... Process newProcess = builder.start();
String command = "cmd /c python "; Process p = Runtime.getRuntime().exec(command); p.waitFor(); BufferedReader bri = new BufferedReader(new InputStreamReader(p.getInputStream())); BufferedReader bre = new BufferedReader(new InputStreamReader(p.getErrorStream())); String line; while ((line = bri.readLine()) != null) { System.out.println(line); } bri.close(); while ((line = bre.readLine()) != null) { System.out.println(line); } bre.close(); p.waitFor(); System.out.println("Done."); p.destroy();
您可以运行python脚本
Process p = Runtime.getRuntime().exec(PYTHON_ABSOLUTE_PATH, script_path)
要获得PYTHON_ABSOLUTE_PATH,只需输入
which python2.7
在终端
- 如何为需要MyClass.class参数的工厂方法注入Spring Bean
- java.lang.NoClassDefFoundError:org / springframework / context / EnvironmentAware
- multithreadingJava应用程序中的SQLite
- 通过其ID来序列化JAXB对象?
- 为什么我会遇到长时间非GC相关的应用程序暂停?
- Spring 3 + Tomcat 6:表单validationexception – java.lang.NoSuchMethodError:javax.el.ExpressionFactory.newInstance()Ljavax / el / ExpressionFactory;
- Java vs C(运行时)编辑:添加代码
- java中的滑动通知栏(一个火狐)
- 如何使用JAX-RS在Java中使用Web Service从数据库插入数据
- 如何确定GraphicsEnvironment是否存在
- FacesContext中getExternalContext中的NullpointerException