在Google的Colab笔记本中,如何从Python文件中调用函数?

Cho*_*ppy 15 google-colaboratory

从Colab笔记本,我想调用我在一个单独的python文件中编写的python函数.我怎么做?

Bob*_*ith 17

编辑:如果要导入本地模块,则需要编辑sys.path指向该新目录.这是一个示例笔记本:https: //colab.research.google.com/notebook#fileId=1PtYW0hZit-B9y4PL978kV2ppJJPhjQua

原文回复:当然,这是一个示例笔记本:https: //colab.research.google.com/notebook#fileId = 1KBrq8aAiy8vYIIUiTb5UHG9GKOdEMF3n

有两个单元格:第一个定义具有.py要导入的函数的文件.

%%writefile example.py
def f():
  print 'This is a function defined in a Python source file.'
Run Code Online (Sandbox Code Playgroud)

第二个单元用于在笔记本的Python解释器中execfile评估该.py文件.

# Bring the file into the local Python environment.
execfile('example.py')

# Call the function defined in the file.
f()
Run Code Online (Sandbox Code Playgroud)