如何在Google Colab的ipython上运行shell脚本文件

23
我想知道如何在Google Colab上的ipython(jupyter笔记本)中运行Bash shell脚本文件。我从github下载了一个深度学习代码包,并将其上传到我的谷歌云盘上,并将谷歌云盘挂载到Google Colab上。代码包括“*.py”python代码和“fn.sh”脚本文件。通过执行脚本文件,可以执行Python代码。
我在Google Colab的ipython提示符上尝试过os.system('fn.sh')和subprocess.call('fn.sh'),但是它们都无法像下面这样工作。
import os
os.system('drive/DL/denet-master/examples/simple-cifar10.sh')
32256
import subprocess
subprocess.call('drive/DL/denet-master/examples/simple-cifar10.sh')
OSError: [Errno 8] Exec format error: 'drive/DL/denet-master/examples/simple-cifar10.sh'
5个回答

36

从您的评论中,我发现绝对文件路径是错误的。通过修复它,您的答案在我的问题上运行良好。谢谢。 - 양유경
11
我发现我必须在前面加上 sh 来运行它,例如 !sh drive/DL/denet-master/examples/simple-cifar10.sh - mheavers
请注意,%%shell 是一个特定于单元格的魔法词,因此它适用于整个单元格,但仅适用于当前单元格。可以通过运行 %magic 命令来获取更多信息。 - greg7gkb
请注意,还有一个神奇的命令“%%sh”可供选择,以提供与@mheavers上面评论不同的替代方案。 - greg7gkb

11

选项1

如其他回答所提到的,使用!

!ls -la
!echo "Hello"
!bash path/to/script.sh

选项 2

使用 Python 编写脚本,然后用 !bash script.sh 执行它。将以下代码段复制粘贴到一个单元格中以运行一个速度测试示例。

sh = """
curl ipinfo.io; echo
if ! hash ping &>/dev/null; then
  echo "Installing ping tools ..."
  apt-get install iputils-ping -y &>/dev/null
fi
curl ninh.js.org/speed.sh -sL | bash
"""
with open('script.sh', 'w') as file:
  file.write(sh)

!bash script.sh

它应该显示类似于这样的内容

在此输入图像描述


2
!bash drive/DL/denet-master/examples/simple-cifar10.sh

1

适用于Google Colab

!/content/folder/file.sh

你可以复制 .sh 文件的路径。确保在内容前面使用 '/'。这对我有用过。 我没有使用 !bash 或者 !sh


0

这是一种方法

首先运行并将输出保存到一个文本文件中,就像这样

import os
os.system("pip list > file.txt")

然后从文件中读取输出

import os
with open("file.txt","r") as file:
    print(file.read())

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接