python - Google Colab:从另一个 python 文件调用函数
问题描述
我想DataProcesser
从load_data.py
python 文件中运行一个函数,该文件可以在我的 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.
> -------------------------------------------------------------
解决方案
您可能不需要转义字符串中的空格,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
文件夹并复制了属性,然后将其粘贴到代码中。
推荐阅读
- python - 如何将返回的变量传递给 Jupyter Notebook 中的其他方法
- sql - SQL - round down to two decimal places
- mapbox - Get bounding box for a layer in Mapbox-GL-JS
- flask - 引导程序/烧瓶格式问题
- git - What does `git commit file.txt` do if file.txt is not staged?
- javascript - LeafletJS Marker latitude and longitude is incorrect when placed within China
- php - getting error "Uncaught PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064"
- java - 如何从服务器端 java 返回正确的 JSON 到 DataTables?
- sql - R 中有没有办法将扁平的层次结构表转换为完整的扩展输出以用于映射?
- python - 将多索引和单索引数据帧相乘