如何从Gradle激活虚拟环境?

时间:2018-02-27 16:19:05

标签: python macos gradle virtualenv pybuilder

我的gradle.build文件中有以下exec命令。

exec {
        workingDir System.getProperty("user.dir")
        commandLine 'python3.6', 'buildscript.py'
    }
exec {
    workingDir System.getProperty("user.dir")
    commandLine 'python3.6', '-m', 'virtualenv', 'env'
}


exec {
    workingDir System.getProperty("user.dir")
    commandLine 'source', 'env/bin/activate'
}

exec {
    workingDir System.getProperty("user.dir")
    commandLine 'pip3.6', 'install', 'pybuilder'
}

exec {
    workingDir System.getProperty("user.dir")
    commandLine 'pyb', '-E', 'env', '-X'
}

这些都在执行gradle构建时运行的构建任务中。 从理论上讲,这应该运行我创建的脚本,创建构建我的python程序所需的所有文件,然后应该创建一个虚拟环境,激活它,安装pybuilder,然后运行pybuilder。但是,命令:

exec {
        workingDir System.getProperty("user.dir")
        commandLine 'source', 'env/bin/activate'
    }

似乎失败了。它声称目录/文件不存在,尽管它通过命令行工作。我不确定为什么会这样。这一点的重点是迫使Pybuilder将我的程序依赖项安装到我创建的虚拟环境中。 pyb -E env在技术上应该为我激活虚拟环境,但无论出于何种原因,它都不会将我的依赖项安装到该虚拟环境中。在我们的Jenkins节点上,这是一个问题,因为我们不希望全局安装这些,更不用说,我还没有root用户权限。

非常感谢任何帮助。如果你知道让Pybuilder正常工作的另一种方法,那也同样好。

2 个答案:

答案 0 :(得分:1)

临时解决方案:我最终创建了一个小shell脚本来创建和激活虚拟环境。然后我从gradle中执行了该脚本。

答案 1 :(得分:0)

source上调用activate只是在做shell魔术来连接变量。您无需始终调用activate(在这种情况下可能不能调用)。相反,您应在pip3.6pyb命令前加上env/bin以直接调用二进制文件。因此,应该是

exec {
   workingDir System.getProperty("user.dir")
   commandLine 'env/bin/pip3.6', 'install', 'pybuilder'
}

exec {
   workingDir System.getProperty("user.dir")
   commandLine 'env/bin/pyb', '-E', 'env', '-X'
}