如何从Java中执行安装在Python虚拟环境中的Python工具。

huangapple go评论81阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2020年9月3日 11:39:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/63716451.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定