从Java调用Python代码时出现问题(不使用jython) [英] Issue in calling Python code from Java (without using jython)

查看:64
本文介绍了从Java调用Python代码时出现问题(不使用jython)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现这是从Java运行(使用exec()方法)python脚本的方法之一.我在python文件中有一个简单的print语句.但是,我的程序在运行时什么也没做.它既不打印用python文件编写的语句,也不抛出异常.该程序只是终止不执行任何操作:

I found this as one of the ways to run (using exec() method) python script from java. I have one simple print statement in python file. However, my program is doing nothing when I run it. It neither prints the statement written in python file nor throws an exception. The program just terminates doing nothing:

Process p = Runtime.getRuntime().exec("C:\\Python\\Python36-32\\python.exe C:\\test2.py");

即使这没有创建输出文件:

Even this is not creating the output file:

Process p = Runtime.getRuntime().exec("C:\\Python\\Python36-32\\python.exe C:\\test2.py output.txt 2>&1");

出了什么问题?

推荐答案

我认为您可以使用ProcessBuilder类来碰碰运气.

I think you could try your luck with the ProcessBuilder class.

如果我正确阅读了Oracle文档,则默认情况下,std输入和输出直接定向到管道,但.oracle.com/javase/7/docs/api/java/lang/ProcessBuilder.html#redirectInput(java.lang.ProcessBuilder.Redirect)"rel =" nofollow noreferrer>将输出(或输入)设置为您文件上的系统或其他内容.

If I read the Oracle documentation correctly, the std inputs and outputs are directed to pipes by default but the ProcessBuilder has an easy method for you to explicitly set output (or input) to a file on your system or something else.

如果您希望Python程序使用与Java程序相同的输出(可能是stdout和stderr),则可以这样使用stg:

If you want your Python program to use the same output as your Java program (likely stdout and stderr), you can use stg like this:

ProcessBuilder pb = new ProcessBuilder("C:\\Python\\Python36-32\\python.exe", "C:\\test2.py");
pb.redirectOutput(Redirect.INHERIT);
Process p = pb.start();

这篇关于从Java调用Python代码时出现问题(不使用jython)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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