【问题标题】:How to run shell script file on ipython at Google Colab如何在 Google Colab 的 ipython 上运行 shell 脚本文件
【发布时间】:2024-01-01 08:40:01
【问题描述】:

我想知道如何在 Google Colab 的 ipython(jupyter notbook) 上运行 bash 销售脚本文件。 我从 github 下载了一个深度学习代码包并将它们上传到我的谷歌驱动器上,然后我在谷歌 Colab 上安装了 goole 驱动器 代码包包括'*.py' python 代码和'fn.sh' 脚本文件。 通过执行脚本文件可以执行python代码。

我在 Google Colab 的 ipython 提示符下尝试了 os.system('fn.sh') 和 subprocess.call('fn.sh') ,但它们不像下面那样工作。

1)

import os
os.system('drive/DL/denet-master/examples/simple-cifar10.sh')
32256

2)

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'

【问题讨论】:

    标签: ipython jupyter-notebook sh google-colaboratory


    【解决方案1】:
    !bash drive/DL/denet-master/examples/simple-cifar10.sh
    

    【讨论】:

      【解决方案2】:

      选项1

      使用! 作为提到的其他答案。

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

      选项2

      使用python编写脚本,然后用!bash script.sh执行。将以下 sn-p 粘贴到单元格以运行速度测试示例。

      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
      

      应该是这样的

      【讨论】:

        【解决方案3】:

        有办法

        首先运行并将输出保存到这样的文本文件中

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

        然后从文件中读取输出

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

        【讨论】:

          【解决方案4】:

          在 Colab 中,您可以使用 !%%shell 调用 shell 命令。

          您在上面的调用将是:

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

          这是一个示例笔记本:

          https://colab.research.google.com/drive/1N7p0B-7QWEQ9TIWRgYLueW03uJgJLmka

          【讨论】:

          • 从您的 cmets 中我发现绝对文件路径错误。通过修复它,您的答案可以很好地解决我的问题。谢谢。
          • 我发现我必须以sh为前缀运行它,例如!sh drive/DL/denet-master/examples/simple-cifar10.sh
          最近更新 更多