Apache Commons Exec Change PATH并执行virtualenv的pip

时间:2016-11-23 17:41:22

标签: java python linux apache-commons apache-commons-exec

我在使用Apache Commons Exec库将PATH环境变量更改为指向目标目录中创建的Python virtualenv时遇到了一些困难。

理想情况下,我想要的东西相当于激活Python virtualenv,但是在Java中。据我所知,最好的方法是更改​​环境变量,以便在我的othervenv之前发现它的pip和python可执行文件(这是我主要使用的另一个虚拟版本)。

我的PluginUtils课程中有这个方法:

public static String callAndGetOutput(CommandLine commandLine, Map<String, String> environment) throws IOException
    {
        CollectingLogOutputStream outputStream = new CollectingLogOutputStream();
        Executor executor = new DefaultExecutor();
        DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
        PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
        executor.setStreamHandler(streamHandler);
        executor.execute(commandLine, environment, resultHandler);
        try
        {
            // Wait for the subprocess to finish.
            resultHandler.waitFor();
        }
        catch(InterruptedException e)
        {
            throw new IOException(e);
        }
        return outputStream.getOuput();
    }

然后这个类调用这个方法。

import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.environment.EnvironmentUtils;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Map;

public class Example
{

    public void run() throws Exception
    {
        Map<String, String> env = EnvironmentUtils.getProcEnvironment();
//        env.forEach((k,v) -> System.out.println(k + "=" + v));
        System.out.println(PluginUtilities.callAndGetOutput(CommandLine.parse("which python"), env));
        System.out.println(PluginUtilities.callAndGetOutput(CommandLine.parse("which pip"), env));
        Path venvDir = Paths.get("", "target", "testvenv");
        Path venvBin = venvDir.resolve("bin");
        assert(Files.isDirectory(venvDir));
        assert(Files.isDirectory(venvBin));
        env.put("PATH", venvBin.toAbsolutePath().toString()+ File.pathSeparator +env.get("PATH"));
        env.put("VIRTUAL_ENV", venvDir.toAbsolutePath().toString());
//        env.forEach((k,v) -> System.out.println(k + "=" + v));
        System.out.println(PluginUtilities.callAndGetOutput(CommandLine.parse("which python"), env));
        System.out.println(PluginUtilities.callAndGetOutput(CommandLine.parse("which pip"), env));
        Path venvPip = venvBin.resolve("pip");
        System.out.println(PluginUtilities.callAndGetOutput(CommandLine.parse("pip install jinja2"), env));
    }

    public static void main(String[] args) throws Exception
    {
        Example example = new Example();
        example.run();
    }
}

输出如下:

/home/lucas/.virtualenvs/othervenv/bin/python
/home/lucas/.virtualenvs/othervenv/bin/pip
/home/lucas/projects/myproject/mymodule/target/testvenv/bin/python
/home/lucas/projects/myproject/mymodule/target/testvenv/bin/pip
Requirement already satisfied: jinja2 in /home/lucas/.virtualenvs/othervenv/lib/python2.7/site-packages
Requirement already satisfied: MarkupSafe in /home/lucas/.virtualenvs/othervenv/lib/python2.7/site-packages (from jinja2)

我很困惑为什么which pip会在运行pip时调用错误的可执行文件时返回正确的pip可执行文件。我能够直接使用venvPip来安装jinja2,但我想避免传递pip的绝对路径,而是让它在PATH上被发现。

我认为可能存在竞争条件,但我添加了DefaultExecuteResultHandler,因此所有子进程调用都是同步的,这似乎没有帮助。

1 个答案:

答案 0 :(得分:3)

简短回答:构建命令行时,需要引用正确的pythonpip可执行文件。一种简化方法是将venv位置存储在占位符映射中,例如

CommandLine.parse("${VBIN}/pip install jinja2",
    Collections.singletonMap("VBIN", venvBin.toAbsolutePath().toString()))

从技术上讲,也可以通过shell启动命令,例如sh pip install jinja2但这不能移植到非unix系统。

答案很长: Java Runtime#exec(commons.exec最终在大多数平台上调用)用于搜索可执行文件的PATH不受后来传递给生成进程的环境的影响。

启动which pip时会发生这种情况

  1. Runtime#exec查询传递给JVM的PATH并扫描这些目录以查找名为which的可执行文件
  2. Runtime#exec找到/usr/bin/which并使用包含更新路径的新环境启动它{/ 1>
  3. /usr/bin/which查询传递给它的PATH并扫描这些目录以查找名为pip的可执行文件
  4. 由于/usr/bin/which使用更新的PATH进行操作,因此会找到testvenv/bin/pip并打印其位置
  5. 启动pip install jinja2时会发生这种情况:

    1. Runtime#exec查询传递给JVM的PATH并扫描这些目录以查找名为pip的可执行文件
    2. Runtime#exec找到otherenv/bin/pip并使用包含更新路径的新环境启动它{/ 1>
    3. otherenv/bin/pip尝试对otherenv进行操作,因此无法完成任务