是否可以在Google-colab中激活virtualenv?(/ bin / sh:1:来源:找不到)

Rya*_*n Y 7 virtualenv theano google-colaboratory

我正在尝试在Google Colab中安装theano进行测试。我已经安装virtualenv并创建了一个环境:

!pip3 install virtualenv
!virtualenv theanoEnv
Run Code Online (Sandbox Code Playgroud)

但是,即使明确提到了“ activate”命令的位置,也无法激活虚拟环境。

!source /content/theanoEnv/bin/activate theanoEnv
Run Code Online (Sandbox Code Playgroud)

错误消息是:

/bin/sh: 1: source: not found
Run Code Online (Sandbox Code Playgroud)

甚至有可能做?

source /[SomeVirtualEnv]/bin/activate SomeVirtualEnv
Run Code Online (Sandbox Code Playgroud)

joe*_*ere 7

简短的回答,我不相信这是可能的,虽然你总是可以跑

!pip3 install theano
Run Code Online (Sandbox Code Playgroud)

我能够激活 virtualenv,但我不相信您可以将当前笔记本切换为使用新创建的 virtualenv。

!pip3 install virtualenv
!virtualenv theanoEnv
!echo '#!/bin/bash \n . ./theanoEnv/bin/activate theanoEnv \n which python3'  > source_theanoEnv.sh && chmod +x source_theanoEnv.sh && ./source_theanoEnv.sh && which python3
!which python3
Run Code Online (Sandbox Code Playgroud)

我把“which python3”放在 3 个地方,结果是

/content/theanoEnv/bin/python3
/usr/bin/python3
/usr/bin/python3
Run Code Online (Sandbox Code Playgroud)

所以看起来“激活”只是暂时的,Colaboratory/Jupyter 仍在使用 /usr/bin/python3

基本上每个!命令在自己的 shell 中运行,Colaboratory 不知道环境改变了

我希望我可以按照这些步骤 https://help.pythonanywhere.com/pages/IPythonNotebookVirtualenvs/

/content/theanoEnv/bin/pip3 install ipykernel
/content/theanoEnv/bin/python3 -m ipykernel install --user --name=theanoEnv
Run Code Online (Sandbox Code Playgroud)

但我不知道将 kernel_class 设置为什么

%config IPKernelApp.kernel_class='???'
Run Code Online (Sandbox Code Playgroud)

另外,即使上述方法有效,我也不相信有办法重新启动笔记本以使用新内核。

也许更精通 Jupyter/Colaboratory 的人可以解释这是否可行。


Kas*_*kar 7

基本上每个!命令在自己的 shell 中运行,Colaboratory 不知道环境改变了

我想出了一个解决方法。由于每个shell都是临时的,我们将环境激活命令和要在环境中执行的命令拼接起来。

所以在你做完之后

!pip3 install virtualenv
!virtualenv theanoEnv
Run Code Online (Sandbox Code Playgroud)

您可以通过以下方式在环境中安装 theano

!source /content/theanoEnv/bin/activate; pip3 install theano
Run Code Online (Sandbox Code Playgroud)

由于环境内容存储在磁盘上的 theanoEnv 目录中,因此它被保留下来。但是您需要为每个新外壳激活它。对于您需要在环境中运行的每个命令,只需添加前缀

!source /content/theanoEnv/bin/activate;
Run Code Online (Sandbox Code Playgroud)

例如,要获取环境中已安装的 python 包列表(即要运行pip3 list),请运行:

!source /content/theanoEnv/bin/activate; pip3 list 
Run Code Online (Sandbox Code Playgroud)

您可以通过这种方式拼接多个命令:(所有命令都将在同一个 shell 中执行)

!source /content/theanoEnv/bin/activate; COMMAND1; COMMAND2; COMMAND3 
Run Code Online (Sandbox Code Playgroud)

你可以在这里查看我在 Colab 上的笔记本。