【问题标题】:How to import .py in google Colaboratory?如何在 google Colaboratory 中导入 .py?
【发布时间】:2020-09-10 10:54:40
【问题描述】:
我想简化代码。所以我做了一个 utils.py ,但 Google Colaboratory 目录是“/content” 我读了其他问题。但这不是我的解决方案
In Google's Colab notebook, How do I call a function from a Python file?
%%writefile example.py
def f():
print 'This is a function defined in a Python source file.'
# Bring the file into the local Python environment.
execfile('example.py')
f()
This is a function defined in a Python source file.
看起来就像只使用 def()。
使用这个,我总是在单元格中编写代码。
但我想要这段代码
import example.py
example.f()
【问题讨论】:
标签:
import
google-colaboratory
【解决方案1】:
也许你想要一个样本:
!wget https://raw.githubusercontent.com/tensorflow/models/master/samples/core/get_started/iris_data.py -P local_modules -nc
import sys
sys.path.append('local_modules')
import iris_data
iris_data.load_data()
【解决方案2】:
我最近也遇到了这个问题。
我通过以下步骤解决了这个问题,尽管这不是一个完美的解决方案。
src = list(files.upload().values())[0]
open('util.py','wb').write(src)
import util
【解决方案3】:
此代码应适用于 Python 3:
from google.colab import drive
import importlib.util
# Mount your drive. It will be at this path: "/content/gdrive/My Drive/"
drive.mount('/content/gdrive')
# Load your module
spec = importlib.util.spec_from_file_location("YOUR_MODULE_NAME", "/content/gdrive/My Drive/utils.py")
your_module_name = importlib.util.module_from_spec(spec)
spec.loader.exec_module(your_module_name)
【解决方案4】:
import importlib.util
import sys
from google.colab import drive
drive.mount('/content/gdrive')
# To add a directory with your code into a list of directories
# which will be searched for packages
sys.path.append('/content/gdrive/My Drive/Colab Notebooks')
import example.py
这对我有用。
【解决方案5】:
如果您没有内容文件夹,请使用它!希望对您有所帮助!
import sys
sys.path.insert(0,'/content/my_project')
from example import*
【解决方案6】:
第 1 步。我刚刚创建了一个文件夹“common_module”,如图所示:
第 2 步从我的“colab”代码单元中调用了所需的类,
sys.path.append('/content/common_module/')
from DataPreProcessHelper import DataPreProcessHelper as DPPHelper
我的类文件“DataPreProcessHelper.py”看起来像这样
【解决方案7】:
将“sample.py”文件的路径添加到系统路径为:
import sys
sys.path.append('drive/codes/')
import sample