在Google的Colab笔记本中,如何从Python文件中调用函数? [英] In Google's Colab notebook, How do I call a function from a Python file?

查看:213
本文介绍了在Google的Colab笔记本中,如何从Python文件中调用函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

From a Colab notebook, I would like to call a python function that I wrote in a separate python file. How do I do that?

推荐答案

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

Edit: If you would like to import a local module, you'll want to edit your sys.path to point to that new directory. Here's an example notebook: https://colab.research.google.com/notebook#fileId=1PtYW0hZit-B9y4PL978kV2ppJJPhjQua

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

Original reply: Sure, here's an example notebook: https://colab.research.google.com/notebook#fileId=1KBrq8aAiy8vYIIUiTb5UHG9GKOdEMF3n

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

There are two cells: the first defines a .py file with a function to be imported.

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

第二个单元格使用 execfile 来评估文件在笔记本的Python解释器中.

The second cell uses execfile to evaluate that .py file in the notebook's Python interpreter.

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

# Call the function defined in the file.
f()

这篇关于在Google的Colab笔记本中,如何从Python文件中调用函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆