英文:
How to execute a Python tool installed in Python virtual environment from Java
问题
以下是翻译好的内容:
我想从Java源代码中运行安装在Python虚拟环境中的Python工具。有哪些可能用于此目的的Java库?
我已经尝试了以下代码:
Runtime.getRuntime().exec("/Users/xxx/Documents/venv/bin/python3.7 yyy");
但是这段代码不起作用。它是用来从虚拟环境(venv
)运行Python脚本(例如,yyy = script.py
)。因此,它给我一个错误,说没有名为yyy
的文件。但是我的要求是从虚拟环境venv
中运行安装的Python工具。
英文:
I want to run a Python tool installed in a python virtual environment from Java source code. What are the possible Java libraries that I can use for this purpose?
I have already tried below code:
Runtime.getRuntime().exec("/Users/xxx/Documents/venv/bin/python3.7 yyy);
But this code doesn't work. It is to run a Python script (eg., yyy= script.py
) from the virtual environment (venv
). Therefore, it gives me an error saying there is no file called yyy
. But my requirement is to run a Python tool installed in the virtual environment venv
.
答案1
得分: 1
你的需求可能需要进一步澄清,但我怀疑你可以使用 ProcessBuilder
来实现。使用 directory(File)
来控制命令的工作目录。而 inheritIO()
则可以使标准输入输出自动工作。切勿硬编码用户的主文件夹路径。你可以使用 System.getProperty(String)
来获取主文件夹路径。
ProcessBuilder pb = new ProcessBuilder();
pb.directory(new File(System.getProperty("user.home"), "Documents/venv/"));
pb.inheritIO();
try {
Process p = pb.command("bin/python3.7",
"lib/python3.7/site-packages/yyy").start();
p.waitFor();
} catch (Exception e) {
e.printStackTrace();
}
最好使用 System.getenv(String)
而不是依赖于 "Documents/venv"
来包含 pyvenv 根目录。
英文:
Your requirement might need a little clarification, but I suspect you can make it work with a ProcessBuilder
. Use directory(File)
to control the working directory for the command. And inheritIO()
to make stdio work "automatically". Never hardcode a user's home folder. You can use System.getProperty(String)
to retrieve the home folder.
ProcessBuilder pb = new ProcessBuilder();
pb.directory(new File(System.getProperty("user.home"), "Documents/venv/"));
pb.inheritIO();
try {
Process p = pb.command("bin/python3.7",
"lib/python3.7/site-packages/yyy").start();
p.waitFor();
} catch (Exception e) {
e.printStackTrace();
}
It might be better to use System.getenv(String)
instead of relying on "Documents/venv"
to contain the pyvenv root.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论