如何在google Colaboratory中导入.py?

时间:2018-03-01 11:12:20

标签: import google-colaboratory

我想简化代码。所以我做了一个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()

7 个答案:

答案 0 :(得分:0)

我最近也遇到过这个问题。

我通过以下步骤解决了这个问题,虽然它不是一个完美的解决方案。

src = list(files.upload().values())[0]
open('util.py','wb').write(src)
import util

答案 1 :(得分:0)

您可能想要的样本:

!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 :(得分:0)

此代码应与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)

答案 3 :(得分:0)

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

这对我有用。

答案 4 :(得分:0)

如果您不在内容文件夹中,请使用此选项!希望有帮助!

import sys
sys.path.insert(0,'/content/my_project')
from example import*

答案 5 :(得分:0)

STEP 1 。我刚刚创建了一个文件夹'common_module',如图所示:

enter image description here

第2步从我的“ colab”代码单元格中调用了所需的类,

sys.path.append('/content/common_module/')
from DataPreProcessHelper import DataPreProcessHelper as DPPHelper

我的类文件'DataPreProcessHelper.py'看起来像这样

enter image description here

答案 6 :(得分:-1)

添加' sample.py'的路径文件到系统路径:

import sys
sys.path.append('drive/codes/') 
import sample