通过 processbuilder 运行脚本
我正在尝试从 java 程序运行 Python、Ruby、C、C++ 和 Java 脚本,有人建议我使用 Processbuilder 作为运行脚本的好方法。据我了解,Processbuilder 主要运行本机文件(Windows 上的 .exe 等)。但是,我听说过一些有关使用 Processbuilder 运行脚本(非本机)文件的事情。不幸的是,我发现的关于这个主题的一切都非常模糊。
如果有人能阐明一种运行非本地脚本(例如 Python、Ruby 等)的方法,我将不胜感激!
I'm trying to run Python, Ruby, C, C++, and Java scripts from a java program, and Processbuilder was suggested to me as a good way to run the scripts. From what I understand, Processbuilder mostly runs native files (.exe on windows, etc.). However, I have heard a few things about running scripts (nonnative) files using Processbuilder. Unfortunately, everything I find on the subject is incredibly vague.
If someone could clarify a way to run nonnative scripts such as Python, Ruby, etc. I would be most grateful!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以查看
ProcessBuilder
文档在 Sunoracle 上,但基本上,您可以运行脚本语言的解释器并将要运行的脚本传递给它。例如,假设您在
/home/myuser/py_script.py
中有一个脚本,而python
位于/usr/bin/
中非常基本的示例,您可以通过更改工作目录和更改环境来变得更加有趣。
您还可以使用
String
数组或List
的子类型构造ProcessBuilder
。列表中的第一项应该是您要运行的程序/可执行文件,以下所有项目都是该程序的参数。You can check the
ProcessBuilder
documentation over at Sunoracle, but basically, you can run the interpreter for the scripting language and pass the script you want to run to it.For example, let's say you have a script in
/home/myuser/py_script.py
, andpython
is in/usr/bin/
An extremely basic example, you can get fancier with changing the working directory and change the environment.
You can also construct
ProcessBuilder
with aString
array or a subtype ofList<String>
. The first item in the list should be the program/executable you want to run, and all the following items are arguments to the program.为了避免手动输入脚本的整个位置(这也可能导致可移植性问题),我做了以下操作:
To avoid having to manually enter the entire location of the script, which may also result in portability issues, here's what I did: