简体   繁体   English

从Java运行Python命令行实用程序

[英]Running Python command-line utility from Java

I developed a command-line utility which needs to be called from a Java GUI application. 我开发了一个需要从Java GUI应用程序调用的命令行实用程序。 The team in charge on the Java GUI would like to bind my command-line application to a button in the GUI; 负责Java GUI的团队希望将我的命令行应用程序绑定到GUI中的按钮; the Python application is such that at the time we have no time or interest in rewriting it in Java. Python应用程序是这样的,当时我们没有时间或兴趣用Java重写它。

I have no experience whatsoever in Java, so I ask you: 我没有任何Java经验,所以我问你:

What is the best way to bind a command-line based Python application to a button in a Java-based GUI application? 将基于命令行的Python应用程序绑定到基于Java的GUI应用程序中的按钮的最佳方法是什么?

I am very concerned about exception management (how to tell Java that Python failed). 我非常关心异常管理(如何告诉Java Python失败)。

Thanks. 谢谢。

You should be able to execute a spawned process from Java using Runtime.exec() . 您应该能够使用Runtime.exec()从Java执行生成的进程。 Here's some examples . 这是一些例子

Make sure you capture the stdout and stderr (concurrently - see this answer for more details) so you can report on errors. 确保捕获stdout和stderr(同时 - 请参阅此答案以获取更多详细信息),以便报告错误。 You can capture the exit code of the application, so make sure that the application itself correctly reports errors. 您可以捕获应用程序的退出代码,因此请确保应用程序本身正确报告错误。 The error code would be a more reliable way of detecting errors (I would suspect) thatn parsing the output streams. 错误代码将是一种更可靠的方法来检测错误(我怀疑)解析输出流。

Have you considered jython? 你考虑过jython吗? You can: 1) use it to run python scripts (allowing it to call Java classes) 2) compile python into class files, making them usable by normal Java code without jython being present at runtime I've only used it in the first pattern, but I've seen tonnes of docs on the second. 您可以:1)使用它来运行python脚本(允许它调用Java类)2)将python编译成类文件,使它们可以被普通的Java代码使用,而不会在运行时出现jython我只在第一个模式中使用它,但我在第二次看到了大量的文档。

I agree with phlip - you can create a scripting engine in Java and use that to call your Python code. 我同意phlip - 您可以用Java创建脚本引擎并使用它来调用您的Python代码。 Providing that your python code doesn't use any unusual OS-specific library calls or DLLs, this should work fine. 假设您的python代码不使用任何异常的特定于操作系统的库调用或DLL,这应该可以正常工作。 This link: http://jythonpodcast.hostjava.net/jythonbook/chapter10.html should give you more information on the exact mechanism you need. 此链接: http//jythonpodcast.hostjava.net/jythonbook/chapter10.html应该为您提供有关所需机制的更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM