我想从load_data.py
python文件中运行一个函数DataProcesser
,该文件可以在我的google驱动器路径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看到的路径不同。如果你在Colab中展开files
选项卡,你可以导航到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
文件夹,复制属性,然后粘贴到代码中。
简单的方法是更改执行目录。即使您已经挂载了Google Drive,执行也不会在该驱动器中进行。故事发生在/content/
。您可以通过运行pwd
检查这一点。通过运行cd path_to_ the_python_file_where_function_is_defined
来更改它。然后执行import name_of_the_file
试试这个
from google.colab import drive
drive.mount('/content/gdrive')
然后
libdir = "/content/gdrive/My Drive/.../"
%run {libdir}MyModule.py
类似地,您可以对笔记本做:
%run {libdir}MyNotebook.ipynb
现在你可以使用你在MyNotebook.ipynb
中定义的所有内容了