是否可以在本身导入GitHub存储库以起作用的Google Colab中导入python文件?

达米安·戴斯蒙德(Damien Desmond)

我正在尝试集成Google Colab,GitHub和Google Drive。我希望能够做的事情之一是创建文件,特别是Gist,但也可能创建整个存储库,这些文件将其他Gist和存储库作为依赖项进行引用。对于我一直用于实验的玩具示例,我有一个简单的.py脚本,该脚本运行以下命令:

import random

def dice_roll():
  roll = random.randint(1,6)
  return roll

这仅返回1到6之间的整数。但是假设我将这个文件保存为Gist,然后将其导入Colab,以便可以使用。总体而言,该小的导入脚本如下所示:

# Clone the entire repo.
!git clone -l -s https://gist.github.com/dcdesmond/28276a70d5d5611d3e0f4f5717eca535 cloned-repo

# Change directory into cloned repo
%cd cloned-repo

# List repo contents
!ls

这工作得很好,并且在运行它的Colab笔记本单元中,输出将是:

Cloning into 'cloned-repo'...
warning: --local is ignored
remote: Enumerating objects: 3, done.
remote: Counting objects: 100% (3/3), done.
remote: Compressing objects: 100% (2/2), done.
remote: Total 3 (delta 0), reused 0 (delta 0), pack-reused 0
Unpacking objects: 100% (3/3), done.
/content/cloned-repo
dice_roll.py

因此,如果

import dice_roll
dice_roll.dice_roll()

在下一个单元格中运行,它将输出1到6之间的整数。但是此输出取决于外部GitHub Gist中包含的模块。因此,如果我想开始分层我的Gists(或者一段时间内甚至整个仓库),以便模块可以自动到达GitHub链接以获取所需的依赖关系,则可以合理地认为我可以将上述所有内容作为组合下载.py文件,它将作为一个脚本(称为dice_roller.py)运行,如下所示:

# Clone the entire repo.
!git clone -l -s https://gist.github.com/dcdesmond/28276a70d5d5611d3e0f4f5717eca535 cloned-repo

# Change directory into cloned repo
%cd cloned-repo

# List repo contents
!ls

import dice_roll
dice_roll.dice_roll()

然后重复此过程:在Colab笔记本中克隆此复合.py文件并运行它(及其所有分层依赖项),假设会产生相同的输出(1到6之间的整数),或者在更复杂的情况下,是参考资料库及其文件的网络。

但是,如果我将所有内容保存到一个dice_roller.py脚本中,另存为Gist存储库,并以相同的方式克隆该Gist:

!git clone -l -s https://gist.github.com/dcdesmond/bda461a04705ab570747a4e7685b0372 cloned-repo
%cd cloned-repo
!ls

具有相同的工作输出:

Cloning into 'cloned-repo'...
warning: --local is ignored
remote: Enumerating objects: 6, done.
remote: Counting objects: 100% (6/6), done.
remote: Compressing objects: 100% (4/4), done.
remote: Total 6 (delta 1), reused 0 (delta 0), pack-reused 0
Unpacking objects: 100% (6/6), done.
/content/cloned-repo
dice_roller.py

然后我遇到语法解析错误,因为python无法读取git clone命令:

import dice_roller
  File "/content/cloned-repo/cloned-repo/dice_roller.py", line 12
    !git clone -l -s https://gist.github.com/dcdesmond/28276a70d5d5611d3e0f4f5717eca535 cloned-repo
    ^
SyntaxError: invalid syntax

是否存在以Colab可以容纳的方式在脚本之间自动与存储库及其内容进行交互的pythonic方法?

如果还有另一种方法可以实现此目的,那就是编写脚本来提取包含在其他存储库中的文件然后使用它们的脚本,那么我可能会在这里重新发明轮子。在我看来,这是文件系统导航/命令与python本身之间的冲突,而不是Google Colab问题。由于Colab只是IPython / Jupyter在线的,所以我想有人会在本地遇到类似的问题。如果有另一种方法来考虑问题,那么我只需要导入一个存储库或一个文件(而无需复制我可能想要的所有内容的临时存储库),就可以解决问题。

科拉科特

您需要替换!替换%cd为普通的Python等效项。

  • 成为getoutput
  • %cd变成os.chdir(“ ...”)

这是结果

%%writefile dice_roller2.py
import os
from subprocess import getoutput
getoutput("git clone -l -s https://gist.github.com/dcdesmond/28276a70d5d5611d3e0f4f5717eca535 cloned-repo")
os.chdir('cloned-repo')
import dice_roll
print(dice_roll.dice_roll())

这是一个可运行的笔记本

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章