首页 > 解决方案 > Google Colab:从另一个 python 文件调用函数

问题描述

我想DataProcesserload_data.pypython 文件中运行一个函数,该文件可以在我的 google drive path 中找到gdrive/My\ Drive/Colab\ Notebooks/CODEX/source/

from google.colab import drive
drive.mount('/content/gdrive')

# Custom functions/classes
path_to_module = 'gdrive/My\ Drive/Colab\ Notebooks/CODEX/source/'  # Path where all the .py files are, relative to the notebook folder
sys.path.append(path_to_module)
from load_data import DataProcesser

追溯:

> --------------------------------------------------------------------------- ModuleNotFoundError                       Traceback (most recent call
> last) <ipython-input-30-066e93c75b7d> in <module>()
>      20 path_to_module = 'gdrive/My\ Drive/Colab\ Notebooks/CODEX/source/'  # Path where all the .py files are, relative
> to the notebook folder
>      21 sys.path.append(path_to_module)
> ---> 22 from load_data import DataProcesser
>      23 from train_utils import even_intervals
>      24 from models import *
> 
> ModuleNotFoundError: No module named 'load_data'
> 
> --------------------------------------------------------------------------- NOTE: If your import is failing due to a missing package, you can
> manually install dependencies using either !pip or !apt.
> 
> To view examples of installing some common dependencies, click the
> "Open Examples" button below.
> -------------------------------------------------------------

标签: pythongoogle-colaboratory

解决方案


您可能不需要转义字符串中的空格,path_to_module但可能是 Colab 看到的路径不同。如果您files在 Colab 中展开选项卡,您可以导航到 Google Drive 中的文件。然后您可以右键单击您想要的文件或文件夹并执行Copy path。然后,您可以将其粘贴到path_to_module定义的单元格中。

可以说,它对我有用;但我的路径 ( .../tmp) 将与您的不同。

from google.colab import drive
drive.mount('/content/gdrive')
import sys    
path_to_module = '/content/gdrive/MyDrive/tmp'
sys.path.append(path_to_module)
from mypy import myfunc

我导航到tmp文件夹并复制了属性,然后将其粘贴到代码中。


推荐阅读