在 colab 裡執行 python 還滿簡單的,可以使用 ! 或 % 符號開頭的指令,來執行系統上的外部指令,python 版本是 python3.
- %cd 可以切換現行目錄
- !python 執行python 指令
- !cat 檢視文件內容
Colab lets you do everything which you can in a locally hosted Jupyter notebook, you can also use shell commands like ls, dir, pwd, cd, cat, echo
, et cetera using line-magic (%) or bash (!).
When you run your notebook from Google drive, an instance is created only for the notebook. To make the other files in your Google drive folder available you can mount your Google drive with:
from google.colab import drive
drive.mount('/content/gdrive')
goto the directory
%cd '/gdrive/My Drive/Colab Notebooks/run-python-on-colab/'
And run your script:
!python file.py
使用Google Colab訓練PyTorch神經網路
Colab是在Google硬碟上面執行的,所以,需要到Google硬碟上面新建Colaboratory檔案,並進行關聯,檔案是以ipynb結尾的Jupyter筆記本,請在 .ipynb 的檔案裡,執行下面指令,來安裝PyTorch:
!pip3 install torch torchvision
資料來源
- Can I run python scripts in colab?
https://stackoverflow.com/questions/59628273/can-i-run-python-scripts-in-colab - How to run a Python script in a ‘.py’ file from a Google Colab notebook?
https://stackoverflow.com/questions/51194303/how-to-run-a-python-script-in-a-py-file-from-a-google-colab-notebook